使用字符串拆分

本文关键字:拆分 字符串 | 更新日期: 2023-09-27 17:59:18

我有一个文本

类别2,"带逗号的东西"

当我把它除以"时,它应该会给我两个字符串

  • 类别2
  • "带有逗号的东西"

但实际上它将字符串从每个逗号中分离出来。

我怎样才能达到预期的结果。

Thanx

使用字符串拆分

只需调用variable.Split(new char[] { ',' }, 2)即可。MSDN中的完整文档。

您可能想在这里做很多事情,所以我将解决其中一些问题:

在第一个逗号上拆分

String text = text.Split(new char[] { ',' }, 2);

在每个逗号上拆分

String text = text.Split(new char[] {','});

在不在" 中的逗号上拆分

var result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)"); 

最后一个取自C#Regex Split

指定数组中需要的最大字符串数:

string[] parts = text.Split(new char[] { ',' }, 2);

String.Split工作在最简单、最快的级别,因此它将您传递给它的所有分隔符上的文本拆分,并且它没有双引号等特殊规则的概念。

如果你需要一个理解双引号的CSV解析器,那么你可以自己编写,或者有一些优秀的开源解析器可用——例如。http://www.codeproject.com/KB/database/CsvReader.aspx-这是我在几个项目中使用过并推荐的一个。

试试这个:

public static class StringExtensions
{
    public static IEnumerable<string> SplitToSubstrings(this string str)
    {
        int startIndex = 0;
        bool isInQuotes = false;
        for (int index = 0; index < str.Length; index++ )
        {
            if (str[index] == ''"')
                isInQuotes = !isInQuotes;
            bool isStartOfNewSubstring = (!isInQuotes && str[index] == ',');                
            if (isStartOfNewSubstring)
            {
                yield return str.Substring(startIndex, index - startIndex).Trim();
                startIndex = index + 1;
            }
        }
        yield return str.Substring(startIndex).Trim();
    }
}

用法非常简单:

foreach(var str in text.SplitToSubstrings())
    Console.WriteLine(str);