-6

作为这个问题的延续

假设我有一个字符串:

String myString = "violet are blue|roses are red|this is a terrible poet";

我想修剪它说“玫瑰是红色的|”的特定部分 使它成为:

myString = "violet are blue|this is a terrible poet";
4

4 回答 4

3

你可以使用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);
于 2012-12-15T18:53:51.630 回答
2

我假设|您要使用这些字符来查找要删除的内容。

|使用获取第一个索引IndexOf,然后是第二个,然后使用 获取字符串的其余部分Remove

int index1 = myString.IndexOf('|');
int index2 = myString.IndexOf('|', index1 + 1);
myString = myString.Remove(index1, index2 - index1);
于 2012-12-15T18:55:15.070 回答
1

使用拆分:

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];
于 2012-12-15T18:56:06.603 回答
0

如果没有正则表达式的答案,这个问题就不会是一个完整的问题:)

String myString = "violet are blue|roses are red|this is a terrible poet";
var newstr = Regex.Replace(myString, @"\|.+?\|", "|");
于 2012-12-15T19:45:24.140 回答