代码之家  ›  专栏  ›  技术社区  ›  MGSoto

从数组输出csv字符串最常用的方法是什么?

  •  1
  • MGSoto  · 技术社区  · 16 年前

    试图保持完全的语言不可知性,并避免使用诸如split()和join()这样的内置方法,构建csv字符串最常用或接受的方法是什么?我经常遇到这样的情况,我很好奇split()这样的方法是如何实现这一点的?我通常这样做:

    for(int i = 0; i < list.length; i++)
    {
        if(i == list.length - 1)
        {
            Write(list[i]);
        }
        else
        {
            Write(list[i] + ',');
        }
    }
    

    但似乎应该有更好的方法。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Reed Copsey    16 年前

    我见过的大多数实现都有以下功能:

    if (list.length > 0)
    {
        Write(list[0]);
        for(int i = 1; i < list.length; i++)
        {
            Write(','); // Write separator character(s)
            Write(list[i]);
        }
    }
    

    这样可以避免在for循环中进行检查。.NET框架的join()方法使用了这种基本方法(当然还有更多的检查)。

        2
  •  0
  •   Kyle C    16 年前

    您可能不想使用split、join或任何简单的方法。如果您的值包含逗号或引号怎么办?

    如果可能,请使用库。否则,类似于:

    string escapeForCsv(string s) {
        if s.contains("\",\n") {
          needs_quotes = true
          s.replace("\"", "\"\"")
        }
        if needs_quotes {
          s = "\"" + s + "\""
        }
        return s
    }
    
    for (i := 0; i < array.length; i++) {
        elt = array[i]
        if i > 0 {
           Write(',')
        }
        Write(escapeForCsv(elt))
    }
    
    推荐文章