简体   繁体   English

如何在字符串数组中拆分字符串?

[英]How to split string inside string array?

Below is my string array : 下面是我的字符串数组:

 public string[] categories { get; set; }

Now this categories contains records like below : 现在,此类别包含如下记录:

 "categories": [
    "electronic,sports",
    "abc,pqr",
    "xyz",
  ]

Input : 输入

string[] categories = { "electronic,sports", "abc,pqr", "xyz"};

Now I want to split values in categories and create records like this but in categories variable only : 现在,我想在类别中拆分值并创建像这样的记录,但类别变量中

So final categories variable should contain output like below: 因此最终类别变量应包含如下输出:

"categories": [
    "electronic",
    "sports",
    "abc",
    "pqr",
    "xyz",
  ]

So I want my loop to run 5 times; 所以我希望循环运行5次; if I loop on to categories variable and further lots of operation is done on this variable only so I don't want to take above final output in other variable. 如果我循环到类别变量,并且仅对该变量执行进一步的操作,那么我就不想在其他变量上获得最终的输出。

 foreach (var category in categories)
 {
     //code
 }

You can use LINQ SelectMany() and then project the result to array : 您可以使用LINQ SelectMany() ,然后将结果投影到array:

using System.Linq;


string[] categories = { "electronic,sports", "abc,pqr", "xyz"};
categories = categories.SelectMany(o => o.Split(',')).ToArray();

foreach(var c in categories)
{
    Console.WriteLine(c);
}

demo

output : 输出:

electronic
sports
abc
pqr
xyz

You can try without if code; 您可以尝试不使用if代码;

        List<string> temps = new List<string>();
        foreach (var category in categories)
        {
            temps.AddRange(category.Split(',').ToList());
        }
        categories = temps.ToArray();

Without linq...just using a couple foreach loops. 没有linq ...只需使用几个foreach循环。

        string[] categories = new string[] { "electronic,sports", "abc,pqr", "xyz" };

        foreach(var category in categories)
        {
            foreach(var item in category.Split(','))
            {
                Console.WriteLine(item);
            }
        }

This might do the trick for you 这可能为您解决问题

List<string> newcategories = new List<string>();
foreach(var category in categories)
{
    if(category.Contains(","))
    {
        string[] c = category.Split(',');
        newcategories.Add(c[0]);
        newcategories.Add(c[1]);
    }
    else
    {
        newcategories.Add(category);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM