我需要根据分隔符的某些字符数组拆分字符串,而不是在字符串中丢失这些分隔符

时间:2016-10-26 18:50:53

标签: c# string split

例如:

string input = "+hello-ali!56*89";

我希望输出如下:

+ 
hello
-
ali
!
56
*
89

4 个答案:

答案 0 :(得分:3)

您可以使用Regex,

string input = "+hello-ali!56*89";
var result = Regex.Matches(input, @"\w+|.+?")
                .Cast<Match>()
                .Select(m => m.Value)
                .ToList();

答案 1 :(得分:1)

var input = "+hello-ali!56*89";

var a = Regex.Split(input, @"(\W)");  // { "","+","hello","-","ali","!","56","*","89" }

var b = Regex.Split(input, @"(\w+)"); // { "+","hello","-","ali","!","56","*","89","" }

\W匹配任何“非单词字符”:
https://msdn.microsoft.com/en-us/library/20bw873z#NonWordCharacter

答案 2 :(得分:0)

var param = new [] {',', '!'}

您可以使用.Split(param)并获取由您的字符分隔的字符串数组,然后您可以按照您想要的顺序将它们混合在一起

答案 3 :(得分:0)

这是您的另一个选择。

var values = new List<string>();

string input = "+hello-ali!56*89";
var delimiters = new char[] { '+', '-', '*', '!' };
//split the strings using the delimiters, eliminate empty strings
var tempValues = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

var curChar = 0;
// iterate through the input string finding your original strings
// include the delimiter
foreach (var val in tempValues)
{
    var matchCharStart = input.IndexOf(val, curChar,   StringComparison.Ordinal);
    if (matchCharStart <= 0) continue;
        values.Add(input.Substring(matchCharStart - 1, val.Length + 1));
        if (matchCharStart > 0) curChar = matchCharStart + val.Length;
    }
}