根据逗号分割文字 [英] Splitting text based on comma

查看:64
本文介绍了根据逗号分割文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C#的CSV解析器/阅读器?

我想使用 Split 函数分割文本:

I want to split the text using the Split function:

string str = "ZBEE10364,\"Cobler, CHARLOTTE J\",Whiskey,,Brandy,0:00:00,20110912,CHECK,2918,117.33,1,117.33,0,EDM0,Yu789";
string[] strArr = str.Split(',');

这很好,但是 Cober CHARLOTTE 在不同的记录中。我不要这是一个CSV文件,当我使用Excel打开它时,它可以正常运行。

This works fine but "Cober and "CHARLOTTE are in different records. I don't want that. It is a CSV file and when I open it using Excel it works perfectly.

Cobler,CHARLOTTE J 出现在一列。我该如何解决呢?

Cobler, CHARLOTTE J appears in a single column. How can I solve this?

推荐答案

此辅助方法可以解决问题:

This helper method does the trick:

public static class StringSplitHelper{

  public static string[] SplitNonQuoted(this string str, char separator){
    if(string.IsNullOrEmpty(str)) return new string[]{};
    if(separator == '\"') throw new ArgumentException("Separator cannot be a quotation mark", "separator"); 
    List<string> fields = new List<string>();
    bool inQuotes = false;
    StringBuilder sb = new StringBuilder();
    foreach(var c in str){
        if(c == '\"')
        {
            inQuotes = !inQuotes;
        }
        else if(c == separator){
            if(inQuotes) {
                sb.Append(c);
            }
            else {
                fields.Add(sb.ToString());
                sb.Clear();
            }
        }
        else{
            sb.Append(c);
        }
    }
    return fields.ToArray();
  }
}

然后,而不是 strArr = str.Split(',');
do strArr = str.SplitNonQuoted(此字符串str,',');

这篇关于根据逗号分割文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆