C#-使用String.Split(CharArray)

时间:2018-11-04 21:09:48

标签: c# split

如果我在字符串上使用Split()函数,将各种拆分字符作为char[]参数传入,并且考虑到从字符串中删除了匹配的拆分字符,我如何确定哪个字符它匹配并拆分了?

string inputString = "Hello, there| world";
char[] splitChars = new char[] { ',','|' }
foreach(string section in inputString.Split(splitChars))
{
   Console.WriteLine(section) // [0] Hello [1} there [2] world (no splitChars)
}

我了解也许无法用我的方法保留此信息。如果是这样,您能建议一种替代方法吗?

3 个答案:

答案 0 :(得分:3)

here中记录的C#Regex.Split()方法可以返回分割字符以及它们之间的单词。

string inputString = "Hello, there| world";
string pattern = @"(,)|([|])";
foreach (string result in Regex.Split(inputString, pattern))
{
    Console.WriteLine("'{0}'", result);
}

结果是:

'Hello'
','
' there'
'|'
' world'

答案 1 :(得分:2)

使用Regex.Split()方法。我已经将此方法包装在以下扩展方法中,该方法与string.Split()本身一样易于使用:

public static string[] ExtendedSplit(this string input, char[] splitChars) 
{
    string pattern = string.Join("|", splitChars.Select(x => "(" +  Regex.Escape(x.ToString()) + ")"));
    return Regex.Split(input, pattern);          
}

用法:

string inputString = "Hello, there| world";
char[] splitChars = new char[]{',', '|'};

foreach (string result in inputString.ExtendedSplit(splitChars))
{
    Console.WriteLine("'{0}'", result);
}

输出:

'Hello'
','
' there'
'|'
' world'

答案 2 :(得分:2)

不,但是自己写一个相当琐碎。记住,框架方法不是魔术,有人写的。如果某项与您的需求不完全匹配,请写出一份符合您需求的文件!

static IEnumerable<(string Sector, char Separator)> Split(
    this string s,
    IEnumerable<char> separators,
    bool removeEmptyEntries)
{
    var buffer = new StringBuilder();
    var separatorsSet = new HashSet<char>(separators);

    foreach (var c in s)
    {
        if (separatorsSet.Contains(c))
        {
            if (!removeEmptyEntries || buffer.Length > 0)
                yield return (buffer.ToString(), c);

            buffer.Clear();
        }
        else
            buffer.Append(c);
    }

    if (buffer.Length > 0)
        yield return (buffer.ToString(), default(char));
}