0
    static void TEST(string arg)
    {
        string[] aArgs = new String[3];
        aArgs = arg.Split(null,3);
    }

我曾希望如果arg只有两个项目,aArgs那么在.Split. 但是,如果找到 2 ,似乎会aArgs被强制使用 2 个元素。.Split

我如何保持aArgs3 个项目,是否.Split有 3 个。

另外,如果.Split交回超过 3 件物品会怎样?

4

3 回答 3

3

此代码将执行您在问题中要求的内容...超过索引 3 的任何值都将连接到最后一个值。

static void TEST(string arg)
{
    string[] aArgs = new String[3];
    string[] argSplit = arg.Split(null,3);
    argSplit.CopyTo(aArgs, 0);
}
于 2013-05-24T15:47:03.297 回答
2

这种方法怎么样:

static void TEST(String arg)
{
    String[] mySA = SplitIntoArray(arg, 3, true);  //truncating in this case to force 3 returned items
}

String[] SplitIntoArray(String StringToSplit, Int32 ArraySize, Boolean Truncate)
{
    List<String> retList = new List<String>();
    String[] sa = StringToSplit.Split(null);
    if (sa.Length > ArraySize && Truncate)
    {
        for (Int32 i = 0; i < ArraySize; i++)
                retList.Add(sa[i]);
    }
    else
    {
        foreach (String s in sa)
            retList.Add(s);
    }

    return retList.ToArray();
}

这也可以作为字符串扩展方法很好地工作,只需进行一些小的修改。

我想您还可以通过附加选项来增强它,例如如何处理 > ArraySize items...将所有内容组合到最后一个项目中,例如,默认情况下会这样做。

于 2013-05-24T15:46:07.660 回答
0

I'm not sure what was the question intent, but if you want to avoid array allocation with String.Split method, you should use a custom code as suggested by @DonBoitnott :

var buffer = new string[3];
string testValue = "foo1;foo2;foo3;foo4;";
int count = Split(testValue, ';', buffer);
Debug.Assert(count == 3);
Debug.Assert(buffer[0] == "foo1" && buffer[1] == "foo2" && buffer[2] == "foo3;foo4;");


static int Split(string value, char separator, string[] buffer)
{
    if (value == null)
        return 0;
    if (buffer == null || buffer.Length == 0)
        throw new ArgumentNullException("buffer"); // or nameof(buffer) with c# 6 / .NET 4.6

    const int indexNotFound = -1;
    int bufferLength = buffer.Length;
    int startIndex = 0;
    int index;
    int nextBufferIndex = 0;
    while ((index = value.IndexOf(separator, startIndex)) != indexNotFound)
    {
        if (++nextBufferIndex == bufferLength)
        {
            buffer[nextBufferIndex-1] = value.Substring(startIndex);
            break;
        }
        else
        {
            buffer[nextBufferIndex-1] = value.Substring(startIndex, index - startIndex);
            startIndex = index + 1;
        }
    }
    if (nextBufferIndex<bufferLength && value.Length >= startIndex)
        buffer[nextBufferIndex++] = value.Substring(startIndex);

    return nextBufferIndex;
}

Note that each string in the pre-allocated array is a new string allocation (String.Substring allocates a new string).

于 2017-09-05T12:25:04.883 回答