使用分隔符拆分字符串,但在C#中保留结果中的分隔符

我想用分隔符拆分一个字符串,但在结果中保留分隔符。

我怎么在C#中这样做?

如果您希望分隔符为“自己的分割”,则可以使用Regex.Split,例如:

string input = "plum-pear"; string pattern = "(-)"; string[] substrings = Regex.Split(input, pattern); // Split on hyphens foreach (string match in substrings) { Console.WriteLine("'{0}'", match); } // The method writes the following to the console: // 'plum' // '-' // 'pear' 

此版本不使用LINQ或Regex,因此它可能相对有效。 我认为它可能比正则表达式更容易使用,因为您不必担心转义特殊分隔符。 它返回一个IList ,它比总是转换为数组更有效。 这是一种方便的扩展方法。 您可以将分隔符作为数组或多个参数传递。

 ///  /// Splits the given string into a list of substrings, while outputting the splitting /// delimiters (each in its own string) as well. It's just like String.Split() except /// the delimiters are preserved. No empty strings are output. /// String to parse. Can be null or empty. /// The delimiting characters. Can be an empty array. ///  public static IList SplitAndKeepDelimiters(this string s, params char[] delimiters) { var parts = new List(); if (!string.IsNullOrEmpty(s)) { int iFirst = 0; do { int iLast = s.IndexOfAny(delimiters, iFirst); if (iLast >= 0) { if (iLast > iFirst) parts.Add(s.Substring(iFirst, iLast - iFirst)); //part before the delimiter parts.Add(new string(s[iLast], 1));//the delimiter iFirst = iLast + 1; continue; } //No delimiters were found, but at least one character remains. Add the rest and stop. parts.Add(s.Substring(iFirst, s.Length - iFirst)); break; } while (iFirst < s.Length); } return parts; } 

一些unit testing:

 text = "[a link|http://www.google.com]"; result = text.SplitAndKeepDelimiters('[', '|', ']'); Assert.IsTrue(result.Count == 5); Assert.AreEqual(result[0], "["); Assert.AreEqual(result[1], "a link"); Assert.AreEqual(result[2], "|"); Assert.AreEqual(result[3], "http://www.google.com"); Assert.AreEqual(result[4], "]"); 

我想说实现这个的最简单方法(除了Hans Kesting提出的论点)是以常规方式分割字符串,然后遍历数组并将分隔符添加到除最后一个元素之外的每个元素。

我想做一个这样的多行字符串,但需要保持换行符,所以我这样做了

 string x = @"line 1 {0} line 2 {1} "; foreach(var line in string.Format(x, "one", "two") .Split("\n") .Select(x => x.Contains('\r') ? x + '\n' : x) .AsEnumerable() ) { Console.Write(line); } 

产量

 line 1 one line 2 two 

我遇到了同样的问题,但有多个分隔符。 这是我的解决方案:

  public static string[] SplitLeft(this string @this, char[] delimiters, int count) { var splits = new List(); int next = -1; while (splits.Count + 1 < count && (next = @this.IndexOfAny(delimiters, next + 1)) >= 0) { splits.Add(@this.Substring(0, next)); @this = new string(@this.Skip(next).ToArray()); } splits.Add(@this); return splits.ToArray(); } 

分离CamelCase变量名称的示例:

 var variableSplit = variableName.SplitLeft( Enumerable.Range('A', 26).Select(i => (char)i).ToArray()); 

为避免在新行中添加字符,请尝试以下操作:

  string[] substrings = Regex.Split(input,@"(?<=[-])");