Join a string using delimiters

后端 未结 24 1643
北海茫月
北海茫月 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:52

    I'd always add the delimeter and then remove it at the end if necessary. This way, you're not executing an if statement for every iteration of the loop when you only care about doing the work once.

    StringBuilder sb = new StringBuilder();
    
    foreach(string item in list){
        sb.Append(item);
        sb.Append(delimeter);
    }
    
    if (list.Count > 0) {
        sb.Remove(sb.Length - delimter.Length, delimeter.Length)
    }
    

提交回复
热议问题