作为这个问题的延续
假设我有一个字符串:
String myString = "violet are blue|roses are red|this is a terrible poet";
我想修剪它说“玫瑰是红色的|”的特定部分 使它成为:
myString = "violet are blue|this is a terrible poet";
你可以使用String.Replace
方法
string input = "violet are blue|roses are red|this is a terrible poet";
string expected = "violet are blue|this is a terrible poet";
string actual = input.Replace("roses are red|", String.Empty);
Debug.Assert(expected == actual);
我假设|
您要使用这些字符来查找要删除的内容。
|
使用获取第一个索引IndexOf
,然后是第二个,然后使用 获取字符串的其余部分Remove
:
int index1 = myString.IndexOf('|');
int index2 = myString.IndexOf('|', index1 + 1);
myString = myString.Remove(index1, index2 - index1);
使用拆分:
const string myString = "violet are blue|roses are red|this is a terrible poet";
const char itemToSplitOn = '|';
var arr = myString.Split(itemToSplitOn);
var newString = arr[0] + itemToSplitOn + arr[2];
如果没有正则表达式的答案,这个问题就不会是一个完整的问题:)
String myString = "violet are blue|roses are red|this is a terrible poet";
var newstr = Regex.Replace(myString, @"\|.+?\|", "|");