💻 Programming

String

String

A text data type composed of a sequence of characters. Immutable in most languages, and provides various manipulation methods.

📖 Detailed Explanation

String is a basic data type made up of a sequential series of characters. It is a core data structure for representing and processing text data in programming, used almost everywhere: user input, file contents, API responses, database records, and more. Internally it is implemented as a character array (char array) or a byte sequence, and the representation differs by language.

Immutability is a key property of String. In most modern languages, including Java, Python, JavaScript, and Go, a String cannot be changed once created. When you add " world" to "hello", the existing string is not modified; instead a new string "hello world" is created in memory. This property provides benefits such as thread safety, use as hash keys, and string interning (String Pool).

Character encoding is the method of converting characters to bytes. ASCII represents English letters in 1 byte (0-127), and UTF-8 represents characters from around the world with variable length (1-4 bytes). UTF-16 represents most characters in 2 bytes and some in 4 bytes. JavaScript and Java use UTF-16 internally, while Python 3 and Go use UTF-8 by default. An encoding mismatch is a leading cause of "garbled text" bugs.

Practical considerations: string concatenation performance matters. Using the += operation in a loop creates a new object each time, resulting in O(n²) time complexity. Instead, using Java's StringBuilder, Python's "".join(list), or a JavaScript array's join() improves this to O(n). For large text processing, use streaming or a Buffer for memory efficiency.

💻 Code Example

// 1. 기본 문자열 조작
const str = "Hello, World!";

console.log(str.length);           // 13
console.log(str.toUpperCase());    // "HELLO, WORLD!"
console.log(str.slice(0, 5));      // "Hello"
console.log(str.split(", "));      // ["Hello", "World!"]
console.log(str.includes("World")); // true
console.log(str.indexOf("o"));     // 4

// 2. 템플릿 리터럴 (ES6+)
const name = "김개발";
const age = 28;
const greeting = `안녕하세요, ${name}님!
나이: ${age}세
내년 나이: ${age + 1}세`;
console.log(greeting);

// 3. 정규식 활용
const email = "user@example.com";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test(email)); // true

const text = "가격: 10,000원, 수량: 5개";
const numbers = text.match(/\d+/g);  // ["10", "000", "5"]
const cleaned = text.replace(/,/g, ""); // 쉼표 제거

// 4. 효율적인 문자열 연결
const items = ["사과", "바나나", "오렌지"];

// 비효율적 (매번 새 문자열 생성)
let bad = "";
for (const item of items) {
    bad += item + ", ";  // O(n²)
}

// 효율적 (배열 join 사용)
const good = items.join(", ");  // O(n)
console.log(good); // "사과, 바나나, 오렌지"

// 5. 유니코드 처리
const emoji = "👨‍👩‍👧‍👦";
console.log(emoji.length);        // 11 (서로게이트 페어 + ZWJ)
console.log([...emoji].length);   // 1 (스프레드로 제대로 분리)

// 한글 자모 분리
const korean = "한글";
console.log(korean.normalize("NFD").length); // 6 (자모 분리)
console.log(korean.normalize("NFC").length); // 2 (완성형)
# 1. 기본 문자열 조작
text = "Hello, World!"

print(len(text))              # 13
print(text.upper())           # "HELLO, WORLD!"
print(text[0:5])              # "Hello" (슬라이싱)
print(text.split(", "))       # ["Hello", "World!"]
print("World" in text)        # True
print(text.find("o"))         # 4

# 2. f-string (Python 3.6+)
name = "김개발"
age = 28
greeting = f"""안녕하세요, {name}님!
나이: {age}세
내년 나이: {age + 1}세"""
print(greeting)

# 디버깅용 (Python 3.8+)
print(f"{name=}, {age=}")  # name='김개발', age=28

# 3. 정규식 활용
import re

email = "user@example.com"
pattern = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
print(bool(re.match(pattern, email)))  # True

text = "가격: 10,000원, 수량: 5개"
numbers = re.findall(r'\d+', text)  # ['10', '000', '5']
cleaned = re.sub(r',', '', text)    # 쉼표 제거

# 4. 효율적인 문자열 연결
items = ["사과", "바나나", "오렌지"]

# 비효율적 (매번 새 문자열 생성)
bad = ""
for item in items:
    bad += item + ", "  # O(n²)

# 효율적 (join 사용)
good = ", ".join(items)  # O(n)
print(good)  # "사과, 바나나, 오렌지"

# 대용량 처리: StringIO 사용
from io import StringIO
buffer = StringIO()
for item in items:
    buffer.write(item)
    buffer.write(", ")
result = buffer.getvalue()

# 5. 인코딩/디코딩
korean = "한글"
encoded = korean.encode('utf-8')   # b'\xed\x95\x9c\xea\xb8\x80'
decoded = encoded.decode('utf-8')  # "한글"

# 인코딩 오류 처리
text_with_error = b'\xff\xfe'
safe = text_with_error.decode('utf-8', errors='replace')  # 깨진 문자 대체
// 1. 기본 문자열 조작
String str = "Hello, World!";

System.out.println(str.length());           // 13
System.out.println(str.toUpperCase());      // "HELLO, WORLD!"
System.out.println(str.substring(0, 5));    // "Hello"
System.out.println(str.split(", ")[0]);     // "Hello"
System.out.println(str.contains("World"));  // true
System.out.println(str.indexOf("o"));       // 4

// 2. 문자열 비교 (== vs equals)
String a = "hello";
String b = "hello";
String c = new String("hello");

System.out.println(a == b);        // true (String Pool)
System.out.println(a == c);        // false (다른 객체)
System.out.println(a.equals(c));   // true (내용 비교)

// 3. 정규식 활용
import java.util.regex.*;

String email = "user@example.com";
boolean isValid = email.matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");

String text = "가격: 10,000원";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());  // 10, 000
}

// 4. 효율적인 문자열 연결 (StringBuilder)
String[] items = {"사과", "바나나", "오렌지"};

// 비효율적 (매번 새 String 생성)
String bad = "";
for (String item : items) {
    bad += item + ", ";  // O(n²) - 내부적으로 StringBuilder 생성
}

// 효율적 (StringBuilder 재사용)
StringBuilder sb = new StringBuilder();
for (String item : items) {
    if (sb.length() > 0) sb.append(", ");
    sb.append(item);
}
String good = sb.toString();  // O(n)

// Java 8+ String.join
String joined = String.join(", ", items);

// 5. Text Block (Java 15+)
String json = """
    {
        "name": "김개발",
        "age": 28,
        "skills": ["Java", "Spring"]
    }
    """;

// 6. 인코딩 처리
import java.nio.charset.StandardCharsets;

String korean = "한글";
byte[] utf8Bytes = korean.getBytes(StandardCharsets.UTF_8);
String decoded = new String(utf8Bytes, StandardCharsets.UTF_8);

🗣️ Say It Like This in Practice

💬 In a code review (string concatenation performance)
"The string += operation in this for loop is repeating 10,000 times. Since String is immutable, a new object is created each time, making it O(n²). If you switch to StringBuilder or use String.join(), it improves to O(n), and in my test the run time dropped from 2 seconds to 50ms."
💬 In an interview (explaining immutability)
"String's immutability has three benefits. First, thread safety - it's safe for multiple threads to read at the same time. Second, it can be used as a hash map key - because the hashCode doesn't change. Third, memory savings through the String Pool - only one object is created for the same literal. The downside is that a new object is created for every modification, which increases GC load, but this is solved with StringBuilder."
💬 In a bug report (encoding issue)
"I found why the Korean text is garbled. The file was saved as EUC-KR, but the server was reading it as UTF-8. It can be fixed by re-saving the file as UTF-8 or by specifying the 'EUC-KR' charset in InputStreamReader. Going forward, let's update the guide so that all files are saved as UTF-8 without BOM."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Concatenating strings with += in loops

Concatenating an immutable String with += creates a new object each time (O(n²)). Use StringBuilder, String.join(), or the recommended approach for each language. In a 10,000-iteration loop, the performance difference is more than 100x.

❌
Not specifying the encoding

If you omit the encoding in file reads/writes or HTTP responses, the system default is used → different results in different environments. Always specify UTF-8 explicitly. Include charset=utf-8 in the Content-Type header.

❌
SQL Injection vulnerability

Concatenating user input directly into SQL ("SELECT * FROM users WHERE name='" + input + "'") exposes you to attack. Always use a Prepared Statement or your ORM's parameter binding.

✅
The right way

Concatenate efficiently with StringBuilder/join, specify the encoding explicitly, prevent SQL injection with Prepared Statements, compare content with equals() instead of == (Java), and use [...str].length for Unicode length.

🔗 Related Terms

📚 Learn More