如果我有一个像:
这样的数组 string[] test = new string[5] { "hello", "world", "test", "world", "world"};
如何从同一个字符串中创建一个新数组," world"这就是你在手边知道有多少,这里3?
我想的是:
string[] newArray = new string[3];
for (int i = 0; i < 5; i++)
{
if (test[i].Contains("world"))
{
newArray[i] = test[i];
}
}
问题在于:newArray[i] = test[i];
由于它从0迭代到4,因为newArray限制为3,所以会出错。
如何解决这个问题?
编辑:我需要它来自test(旧数组)位置1,3和4应该存储在newArray中的0,1和2。
答案 0 :(得分:5)
你想使用Linq:
var newArray = test.Where(x => x.Contains("world")).ToArray();
答案 1 :(得分:4)
改为使用List<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();
答案 2 :(得分: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;
}
}
答案 3 :(得分:1)
您对i
和test
使用相同的索引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++;
}
}
答案 4 :(得分: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();
}