Join a string using delimiters

后端 未结 24 1457
北海茫月
北海茫月 2020-12-05 09:57

What is the best way to join a list of strings into a combined delimited string. I\'m mainly concerned about when to stop adding the delimiter. I\'ll use C# for my example

相关标签:
24条回答
  • 2020-12-05 10:42

    Java (from Jon's solution):

        StringBuilder sb = new StringBuilder();
        String delimiter = "";
        for (String item : items) {
            sb.append(delimiter).append(item);
            delimeter = ", ";
        }
        return sb.toString();
    
    0 讨论(0)
  • 2020-12-05 10:43

    You could write your own method AppendTostring(string, delimiter) that appends the delimiter if and only if the string is not empty. Then you just call that method in any loop without having to worry when to append and when not to append.

    Edit: better yet of course to use some kind of StringBuffer in the method if available.

    0 讨论(0)
  • 2020-12-05 10:43

    Groovy also has a String Object.join(String) method.

    0 讨论(0)
  • 2020-12-05 10:45
    string result = "";
    foreach(string item in list)
    {
        result += delimiter + item;
    }
    result = result.Substring(1);
    

    Edit: Of course, you wouldn't use this or any one of your algorithms to concatenate strings. With C#/.NET, you'd probably use a StringBuilder:

    StringBuilder sb = new StringBuilder();
    foreach(string item in list)
    {
        sb.Append(delimiter);
        sb.Append(item);
    }
    string result = sb.ToString(1, sb.Length-1);
    

    And a variation of this solution:

    StringBuilder sb = new StringBuilder(list[0]);
    for (int i=1; i<list.Count; i++)
    {
        sb.Append(delimiter);
        sb.Append(list[i]);
    }
    string result = sb.ToString();
    

    Both solutions do not include any error checks.

    0 讨论(0)
  • 2020-12-05 10:48

    There's little reason to make it language-agnostic when some languages provide support for this in one line, e.g., Python's

    ",".join(sequence)
    

    See the join documentation for more info.

    0 讨论(0)
  • 2020-12-05 10:48

    Since you tagged this language agnostic,

    This is how you would do it in python

    # delimiter can be multichar like "| trlalala |"
    delimiter = ";"
    # sequence can be any list, or iterator/generator that returns list of strings
    result = delimiter.join(sequence)
    #result will NOT have ending delimiter 
    

    Edit: I see I got beat to the answer by several people. Sorry for dupication

    0 讨论(0)
提交回复
热议问题