拆分文件名

ven*_*kat 5 .net c# split string-split silverlight-4.0

我有一个文件名:

NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip
Run Code Online (Sandbox Code Playgroud)

如何将上述文件名拆分为4个字符串组.

NewReport
20140423_17255375
BSIQ
2wd28830-841c-4d30-95fd-a57a7aege412.zip
Run Code Online (Sandbox Code Playgroud)

我试过了:

 string[] strFileTokens = filename.Split(new char[]{'-'} , StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)

但我没有得到上面要求的四个字符串

Gra*_*ICA 12

您可以指定要返回的最大子字符串数:

var strFileTokens = filename.Split(new[] { '-' }, 4, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)

这将避免分裂2wd28830-841c-4d30-95fd-a57a7aege412.zip成额外的"碎片".

(另外,你可以删除, StringSplitOptions.None 因为这是默认值.)


在内部,它在循环内创建一个子字符串数组,它只循环指定的次数(或字符串中可用的最大分隔符数,以较小者为准).

for (int i = 0; i < numActualReplaces && currIndex < Length; i++)
{
    splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex );
    currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]); 
}
Run Code Online (Sandbox Code Playgroud)

变量numActualReplaces是您指定的计数或字符串中存在的实际分隔符数的最小值.(这样,如果你指定一个更大的数字,比如30,但你在字符串中只有7个连字符,你将不会得到一个例外.实际上,当你没有指定一个数字时,它实际上是在 没有你的情况下使用它Int32.MaxValue 实现它.)


你更新了你的问题,说你正在使用Silverlight,它没有超载Count.这真的很烦人,因为在string课程引擎盖下,课程仍然支持它.他们只是没有提供传递你自己价值的方法.它使用硬编码int.MaxValue.

您可以创建自己的方法来恢复所需的功能.我还没有针对所有边缘情况测试此扩展方法,但它确实适用于您的字符串.

public static class StringSplitExtension
{
    public static string[] SplitByCount(this string input, char[] separator, int count)
    {
        if (count < 0)
            throw new ArgumentOutOfRangeException("count");

        if (count == 0)
            return new string[0];

        var numberOfSeparators = input.Count(separator.Contains);

        var numActualReplaces = Math.Min(count, numberOfSeparators + 1);

        var splitString = new string[numActualReplaces];

        var index = -1;
        for (var i = 1; i <= numActualReplaces; i++)
        {
            var nextIndex = input.IndexOfAny(separator, index + 1);
            if (nextIndex == -1 || i == numActualReplaces)
                splitString[i - 1] = input.Substring(index + 1);
            else
                splitString[i - 1] = input.Substring(index + 1, nextIndex - index - 1);
            index = nextIndex;
        }

        return splitString;
    }
}
Run Code Online (Sandbox Code Playgroud)

确保它在UserControl可以访问的地方,然后像这样调用它:

var strFileTokens = filename.SplitByCount(new[] { '-' }, 4)
Run Code Online (Sandbox Code Playgroud)