0

If I got an array like:

string[] test = new string[5] { "hello", "world", "test", "world", "world"};

How can I make a new array out of the ones that is the same string, "world" that is where you on before hand know how many there are, here 3?

I was thinking of something like:

string[] newArray = new string[3];

        for (int i = 0; i < 5; i++)
        {
            if (test[i].Contains("world"))
            {
                newArray[i] = test[i];
            }
        }

The problem is here: newArray[i] = test[i];

Since it's iterating from 0 to 4, there's gonna be an error since newArray is limited to 3.

How do solve this?

EDIT: I need it to be that from test (the old array) position 1, 3 and 4 should be stored at 0, 1 and 2 in the newArray.

4

5 回答 5

5

你想使用 Linq:

var newArray = test.Where(x => x.Contains("world")).ToArray();
于 2013-07-25T22:57:39.560 回答
4

使用 aList<string>代替:

    List<string> newList = new List<string>();

    for (int i = 0; i < 5; i++)
    {
        if (test[i].Contains("world"))
        {
            newList.Add(test[i]);
        }
    }

如果您以后真的需要它作为数组.. 转换列表:

string[] newArray = newList.ToArray();
于 2013-07-25T22:57:20.140 回答
1

使用额外的辅助索引变量

    string[] newArray = new string[3];

    for (int i = 0, j = 0; i < 5; i++)
    {
        if (test[i].Contains("world"))
        {
            newArray[j++] = test[i];
            if (j >= newArray.Length)
                break;
        }
    }
于 2013-07-25T22:58:13.907 回答
1

您对 和 使用相同itest索引newArray。我建议您创建另一个计数器变量并增加它:

string[] newArray = new string[3];
int counter = 0;

for (int i = 0; i < 5; i++)
{
    if (test[i].Contains("world"))
    {
        newArray[counter] = test[i];
        counter++;
    }
}
于 2013-07-25T22:58:58.167 回答
1

从技术上讲,这不是您的问题,但是如果您希望根据具有相同单词的数组来加载数组,您可以这样做

test.GroupBy(x => x).ToList();

这将为您提供一个列表列表.. 使用您的测试数据,这将是

list1 - hello
list2 - world world world
list3 - test

示例使用

var lists =  test.GroupBy(x => x).ToList();
foreach(var list in lists)
{
     foreach(var str in list)
     {
         Console.WriteLine(str);
     } 
     Console.WriteLine();
}
于 2013-07-25T23:04:34.000 回答