如果我有这样的字符串
"This is a string that will be split by this and that"
我想得到分割结果为
- "是一个将被拆分的字符串"
- “还有那个”
- “这是一个字符串”
- “将由此而 split ”
1和2被“this”分割 3和4被“that”分割
我的解决方案是使用一个字符串到字符串的映射,并将结果存储在另一个相同类型的字符串到字符串的映射中。然而,对于更复杂和更长的文本,映射中存储的结果会重复,即如上述 1 和 3 中的子字符串“是一个字符串”重复,这种冗余会产生不正确的统计结果。
您能否提供一个更好的解决方案来标记带有不同长字符串分隔符的长字符串?
最佳答案
string myString = "This is a string that will be splitted by this and that";
string foo = myString.ToUpper();
string[] byThis = foo.Split(new string[] { "THIS" }, StringSplitOptions.RemoveEmptyEntries);
string[] byThat = foo.Split(new string[] { "THAT" }, StringSplitOptions.RemoveEmptyEntries);
string[] all = foo.Split(new string[] { "THAT", "THIS" }, StringSplitOptions.RemoveEmptyEntries);
或者你可以使用正则表达式
string[] all = System.Text.RegularExpressions.Regex.Split(myString, "your pattern", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
关于c# - 使用字符串的 delim 标记字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803370/