{ }codelper

Learn › C#

Data · 12

Building strings

Build a string from pieces, join with a separator, print values on one line.

When you can't write the output string in one go, you build it by adding one piece at a time.
The example below reads some words and prints a string of their first letters, the words joined with commas, and the word lengths on one line separated by spaces.

using System;using System.Text; class Program{    static void Main()    {        string[] words = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        var initials = new StringBuilder();        foreach (string w in words)        {            initials.Append(w[0]); // 한 조각씩 붙여 가요        }        Console.WriteLine(initials);        Console.WriteLine(string.Join(", ", words)); // 사이에만 ", "        int[] lens = new int[words.Length];        for (int i = 0; i < words.Length; i++) lens[i] = words[i].Length;        Console.WriteLine(string.Join(" ", lens)); // 빈칸으로 이어 찍기    }}
stdin
red green blue
stdout
rgb
red, green, blue
3 5 4

Key points

  • Building: start from an empty string and add a piece to the end on each lap (initials += w[0]).
    It is the same shape as collecting a sum with total += x.
  • In Java and C#, += makes a whole new copy of the string so far every time.
    So they have a separate StringBuilder that collects the pieces and turns them into a string only once, at the end.
  • Some languages turn a number into a string for you when you append it; in others you must convert it yourself.
  • Joining puts a separator only between the items of a list and makes one string.
    red, green, blue joined with ", " is red, green, blue.
    Nothing is added at the end.
  • Where there is no join, use a loop.
    Print the separator first, only when the item is not the first one, then the item, and no separator is left at the end.
  • Printing several numbers on one line is the same job.
    Some languages have a short way to print them all at once; in others you print them one by one without a newline.

How each language writes it

PythonAppend with s += piece — convert numbers with str(n) first.
With many pieces, append them to a list and finish with "".join(parts).
", ".join(words) accepts only a list of strings.
One line of output: print(*nums); change the separator with print(*nums, sep=", ")
JavaScriptAppend with s += piece — numbers become strings by themselves.
words.join(", ") also works on arrays of numbers, and join() with empty parentheses joins with commas.
One line of output: console.log(nums.join(" "))
TypeScriptSame as JavaScript
JavaStringBuilder sb = new StringBuilder(); then sb.append(piece) — it takes characters, numbers and strings.
At the end, sb.toString() or simply println(sb).
String.join(", ", words) accepts only strings.
Print numbers one by one with System.out.print, or collect them in a StringBuilder
C#var sb = new StringBuilder(); (using System.Text;) then sb.Append(piece), and sb.ToString() at the end.
string.Join(", ", words) also accepts an array of numbers, so one line of output is Console.WriteLine(string.Join(" ", nums))
C++A std::string can be changed, so s += piece appends in place.
Convert numbers with std::to_string(n) first.
There is no join, so use a loop with if (i > 0) std::cout << ", ";.
You can also collect with << into a std::ostringstream and take the result with .str()
CA string is a char array: reserve enough room, put a character in each slot, and put '\0' at the end.
Append a string with strcat(buf, "cd") and a number with sprintf(buf + len, "%d", n).
There is no join, so use a loop and printf
CraykonAppend with s += piece — numbers become strings by themselves.
words.Join(", ") also works on lists of numbers.
Console.WriteLine(list) prints the items separated by spaces; to print one by one, use Console.Write(value), which does not end the line

Common mistakes

Putting the separator after each item

words = ["red", "green", "blue"]
line = ""
for w in words:
    line += w + ","
print(line)

→ red,green,blue, — one extra comma at the end

Use join, or add the separator before the item only when it is not the first: if line: line += ",", then line += w.

Joining a list of numbers as it isPython · Java

print(", ".join([1, 2, 3]))

→ Python raises TypeError: sequence item 0: expected str instance, int found. In Java, String.join(", ", nums) with int[] nums is a compile error too

In Python use ", ".join(map(str, nums)) or print(*nums, sep=", "); in Java collect into a StringBuilder.
Join in JavaScript, C# and Craykon accepts numbers.

Adding two quoted strings with +C · C++

char *s = "ab" + "cd";

→ Compile error invalid operands to binary + — a C string is an address, and addresses cannot be added. std::string s = "ab" + "cd"; in C++ is a compile error for the same reason

In C: char buf[10] = "ab"; strcat(buf, "cd");.
In C++ make one side a std::string: std::string("ab") + "cd".

How languages differ
With many pieces, how you append makes a big difference in time.
Appending one character 200,000 times, in the same setup as this site's judge, took Java about 1 s with += and 1–2 ms with StringBuilder; C# took 2–3 s with += and 1–2 ms with StringBuilder.
Python, with += outside a function as in the example, took about 0.5 s, and under 10 ms when collecting in a list and calling join.
JavaScript (Node.js) took around 10 ms even with +=.
The times differ from computer to computer.
Also, in C++ always go through std::to_string when appending a number: s += 65 appends not "65" but A, the character with code 65.

Practice