C# 将逗号分隔的字符串解析为某种对象的最简单方法,我可以循环访问各个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2235683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:37:38  来源:igfitidea点击:

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

c#string

提问by ycomp

What is the easiest way to parse a comma delimited string list of values into some kind of object that I can loop through, so that I can access the individual values easily?

将逗号分隔的字符串值列表解析为某种我可以循环的对象的最简单方法是什么,以便我可以轻松访问各个值?

example string: "0, 10, 20, 30, 100, 200"

示例字符串: "0, 10, 20, 30, 100, 200"

I'm a bit new to C#, so forgive me for asking a simple question like this. Thanks.

我对 C# 有点陌生,所以请原谅我问这样一个简单的问题。谢谢。

采纳答案by Andras Zoltan

there are gotchas with this - but ultimately the simplest way will be to use

这有问题 - 但最终最简单的方法是使用

string s = [yourlongstring];
string[] values = s.Split(',');

If the number of commas and entries isn't important, and you want to get rid of 'empty' values then you can use

如果逗号和条目的数量不重要,并且您想摆脱“空”值,那么您可以使用

string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

One thing, though - this will keep any whitespace before and after your strings. You could use a bit of Linq magic to solve that:

但是有一件事 - 这将在您的字符串之前和之后保留任何空格。你可以使用一点 Linq 魔法来解决这个问题:

string[] values = s.Split(',').Select(sValue => sValue.Trim()).ToArray();

That's if you're using .Net 3.5 and you have the using System.Linq declaration at the top of your source file.

如果您使用的是 .Net 3.5 并且在源文件的顶部有 using System.Linq 声明。

回答by Asad

   var stringToSplit = "0, 10, 20, 30, 100, 200";
   var stringToSplit = "0, 10, 20, 30, 100, 200";


    // To parse your string 
    var elements = test.Split(new[]
    { ',' }, System.StringSplitOptions.RemoveEmptyEntries);


    // To Loop through
    foreach (string items in elements)
    {
       // enjoy
    }

回答by martin

Use Linq, it is a very quick and easy way.

使用 Linq,这是一种非常快速和简单的方法。

string mystring = "0, 10, 20, 30, 100, 200";

var query = from val in mystring.Split(',')
            select int.Parse(val);
foreach (int num in query)
{
     Console.WriteLine(num);
}

回答by Quick Joe Smith

The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.

该模式匹配所有非数字字符。这将限制您使用非负整数,但对于您的示例,这将绰绰有余。

string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");

回答by Islam Yahiatene

I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Classif you're working with comma separated values text files.

如果您使用逗号分隔值文本文件,我认为最好使用Microsoft.VisualBasic.FileIO.TextFieldParser 类

回答by Jahmic

Sometimes the columns will have commas within themselves, such as:

有时,列内部会包含逗号,例如:

"Some item", "Another Item", "Also, One more item"

“一些项目”,“另一项目”,“另外,还有一个项目”

In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):

在这些情况下,拆分“,”会破坏一些列。也许更简单的方法,但我只是做了我自己的方法(作为奖励,处理逗号后的空格并返回一个 IList):

private IList<string> GetColumns(string columns)
{
    IList<string> list = new List<string>();

    if (!string.IsNullOrWhiteSpace(columns))
    {
        if (columns[0] != '\"')
        {
            // treat as just one item
            list.Add(columns);
        }
        else
        {
            bool gettingItemName = true;
            bool justChanged = false;
            string itemName = string.Empty;

            for (int index = 1; index < columns.Length; index++)
            {
                justChanged = false;
                if (subIndustries[index] == '\"')
                {
                    gettingItemName = !gettingItemName;
                    justChanged = true;
                }

                if ((gettingItemName == false) &&
                (justChanged == true))
                {
                    list.Add(itemName);
                    itemName = string.Empty;
                    justChanged = false;
                }

                if ((gettingItemName == true) && (justChanged == false))
                {
                    itemName += columns[index];
                }
            }
        }
    }

    return list;
}