2010-03-17 148 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);