💬 Strings

String Operations

Split, join, replace, search, convert

String manipulation is relevant in almost every interview problem. The APIs differ in every language.

Language:
Python
Loading...

All languages — Split & join

JavaScript
const s = "hello world foo";

// Split:
const words = s.split(" ");   // ["hello", "world", "foo"]
const words2 = s.split(/s+/); // robust (mehrere Spaces)

// Join:
["a", "b", "c"].join(" ");    // "a b c"
["a", "b", "c"].join("");     // "abc"
["a", "b", "c"].join("-");    // "a-b-c"
TypeScript
const s: string = "hello world foo";

const words: string[] = s.split(" ");
const joined: string = words.join("-");
Java
String s = "hello world foo";

// Split:
String[] words = s.split(" ");      // ["hello","world","foo"]
String[] words2 = s.split("\s+"); // robust

// Join:
String.join(" ", "a", "b", "c");    // "a b c"
String.join("-", words);            // "hello-world-foo"

// Oder mit Stream:
Arrays.stream(words).collect(Collectors.joining(", "));
Go
import "strings"

s := "hello world foo"

// Split:
words := strings.Split(s, " ")
words2 := strings.Fields(s)   // robust (mehrere Spaces)

// Join:
strings.Join(words, "-")       // "hello-world-foo"
strings.Join([]string{"a","b","c"}, " ")
C++
#include <sstream>
#include <vector>

string s = "hello world foo";

// Split (kein eingebautes — mit stringstream):
vector<string> words;
istringstream iss(s);
string word;
while (iss >> word) words.push_back(word);

// Join (kein eingebautes):
string result;
for (int i = 0; i < words.size(); i++) {
    if (i > 0) result += "-";
    result += words[i];
}