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.
words = input().split()initials = ""for w in words: initials += w[0] # 한 조각씩 붙여 가요print(initials)print(", ".join(words)) # 사이에만 ", "lens = [len(w) for w in words]print(*lens) # 빈칸으로 이어 찍기const words = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);let initials = "";for (const w of words) { initials += w[0]; // 한 조각씩 붙여 가요}console.log(initials);console.log(words.join(", ")); // 사이에만 ", "const lens = words.map((w) => w.length);console.log(lens.join(" ")); // 빈칸으로 이어 찍기import { readFileSync } from "node:fs";const words: string[] = readFileSync(0, "utf8").trim().split(/\s+/);let initials: string = "";for (const w of words) { initials += w[0]; // 한 조각씩 붙여 가요}console.log(initials);console.log(words.join(", ")); // 사이에만 ", "const lens: number[] = words.map((w) => w.length);console.log(lens.join(" ")); // 빈칸으로 이어 찍기import java.util.Scanner; public class Main { public static void main(String[] args) { String[] words = new Scanner(System.in).nextLine().trim().split(" +"); StringBuilder initials = new StringBuilder(); for (String w : words) { initials.append(w.charAt(0)); // 한 조각씩 붙여 가요 } System.out.println(initials); System.out.println(String.join(", ", words)); // 사이에만 ", " int[] lens = new int[words.length]; for (int i = 0; i < words.length; i++) lens[i] = words[i].length(); for (int i = 0; i < lens.length; i++) { if (i > 0) System.out.print(" "); // 첫 값 앞에는 안 찍어요 System.out.print(lens[i]); } System.out.println(); }}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)); // 빈칸으로 이어 찍기 }}#include <iostream>#include <string>#include <vector> int main() { std::vector<std::string> words; std::string w; while (std::cin >> w) words.push_back(w); std::string initials; for (const std::string& x : words) { initials += x[0]; // 한 조각씩 붙여 가요 } std::cout << initials << '\n'; for (size_t i = 0; i < words.size(); i++) { if (i > 0) std::cout << ", "; // 사이에만 ", " std::cout << words[i]; } std::cout << '\n'; std::vector<int> lens; for (const std::string& x : words) lens.push_back(x.size()); for (size_t i = 0; i < lens.size(); i++) { if (i > 0) std::cout << ' '; // 첫 값 앞에는 안 찍어요 std::cout << lens[i]; } std::cout << '\n';}#include <stdio.h>#include <string.h> int main(void) { char words[100][51], initials[101]; int n = 0, lens[100]; while (n < 100 && scanf("%50s", words[n]) == 1) n++; for (int i = 0; i < n; i++) { initials[i] = words[i][0]; // 한 조각씩 붙여 가요 } initials[n] = '\0'; // 문자열의 끝 표시 printf("%s\n", initials); for (int i = 0; i < n; i++) { if (i > 0) printf(", "); // 사이에만 ", " printf("%s", words[i]); } printf("\n"); for (int i = 0; i < n; i++) lens[i] = strlen(words[i]); for (int i = 0; i < n; i++) { if (i > 0) printf(" "); // 첫 값 앞에는 안 찍어요 printf("%d", lens[i]); } printf("\n"); return 0;}words = Console.ReadLine().Split();initials = "";foreach (w in words){ initials += w[0]; // 한 조각씩 붙여 가요}Console.WriteLine(initials);Console.WriteLine(words.Join(", ")); // 사이에만 ", "lens = [];foreach (w in words){ lens.Add(w.Length);}Console.WriteLine(lens); // 목록은 빈칸으로 이어 찍어요red green blue
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 withtotal += 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,bluejoined with", "isred, 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
| Python | Append 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=", ") |
|---|---|
| JavaScript | Append 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(" ")) |
| TypeScript | Same as JavaScript |
| Java | StringBuilder 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() |
| C | A 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 |
| Craykon | Append 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".
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.