2010-03-17 75 views
0

我如何的更改字符串值。 C#

http://host/index.php?p=page 

一个字符串值改为

http://host/index.php?p= 
+0

你能更具体的 - 你想字符串值一直到结束'='标志? – dsolimano 2010-03-17 20:53:03

回答

2

不知道,因为你是不是在这里清楚,但这样做你的要求。

string value = @"http://host/index.php?p=page"; 
value = @"http://host/index.php?p="; 
0

此外,如果你正在寻找“参数化”的字符串。

String.Format("http://host/index.php?p={0}", variableName); 
+0

错字:缺少引号! – 2010-03-17 20:57:32

1
string s = @"http://host/index.php?p=page"; 
s = s.Replace("page", ""); 

,或者更严重的是,你可能想:

string s = @"http://host/index.php?p=page"; 
s = s.Substring(0, s.LastIndexOf('=') + 1); 
5

那是不可能的。

在.NET中,字符串是不可变的,这意味着你不能改变一个字符串。

你可以做的是通过复制所有的字符串除了最后四个字符创建从原来的一个新的字符串值,例如:

url = url.Substring(0, url.Length - 4); 
+2

+1为“字符串不可变”评论... – 2010-03-17 21:01:50

1

我这是怎么理解你的问题,将删除任何在最后的 “=”

string s = @"http://host/index.php?p=page"; 
s = s.Remove(s.LastIndexOf("=")+1); 
1

如果你想第一个 “=” 字符后,剥离了一切:

string s = @"http://host/index.php?p=page" 
s = s.Split('=')[0] + "="; 
1

这里的另一种方式:

String oldString = "http://host/index.php?p=page"; 
String newString = oldString.Substring(0, oldString.IndexOf("?p=") + 3);