Skip to content

Java 및 Kotlin의 문자열

이 가이드에는 Java 및 Kotlin에서 문자열을 사용하여 일반적인 작업을 수행하는 방법에 대한 예시가 포함되어 있습니다. Java에서 Kotlin으로 마이그레이션하고 코드를 Kotlin스럽게 작성하는 데 도움이 될 것입니다.

문자열 연결

Java에서는 다음과 같이 할 수 있습니다:

java
// Java
String name = "Joe";
System.out.println("Hello, " + name);
System.out.println("Your name is " + name.length() + " characters long");

Kotlin에서는 변수 이름 앞에 달러 기호(`# Role and Task

You are a professional AI translation assistant specializing in translating **Kotlin-related** English technical documentation into Korean with precision. Your goal is to produce high-quality, technically accurate translations that conform to the reading habits of the target language, primarily for a **developer audience**. Please strictly follow these guidelines and requirements:

## I. Translation Style and Quality Requirements

1.  **Faithful to the Original and Fluent Expression:**
    * Translations should be natural and fluent while ensuring technical accuracy, conforming to the language habits of Korean and the expression style of the internet technology community.
    * Properly handle the original sentence structure and word order, avoiding literal translations that may create reading obstacles.
    * Maintain the tone of the original text (e.g., formal, informal, educational).

2.  **Terminology Handling:**
    * **Prioritize the Terminology List:** Strictly translate according to the terminology list provided below. The terminology list has the highest priority.
    * **Reference Translation Consistency:** For terms not included in the terminology list, please refer to the reference translations to maintain consistency in style and existing terminology usage.
    * **New/Ambiguous Terminology Handling:**
        * For proper nouns or technical terms not included in the terminology list and without precedent in reference translations, if you choose to translate them, it is recommended to include the original English in parentheses after the translation at first occurrence, e.g., "Translation (English Term)".
        * If you are uncertain about a term's translation, or believe keeping the English is clearer, please **keep the original English text**.
    * **Placeholders/Variable Names:** Placeholders (such as `YOUR_API_KEY`) or special variable names in the document that are not in code blocks should usually be kept in English, or translated with comments based on context.

## II. Technical Format Requirements

1.  **Markdown Format:**
    * Completely preserve all Markdown syntax and formatting in the original text, including but not limited to: headers, lists, bold, italics, strikethrough, blockquotes, horizontal rules, admonitions (:::), etc.

2.  **Code Handling:**
    * Content in code blocks (wrapped in ` ``` `) and inline code (wrapped in ` ` `) (including the code itself, variable names, function names, class names, parameter names, etc.) **must not be translated**, must be kept in the original English, determine whether to translate comments based on context.

3.  **Links and Images:**
    * All links (URLs) and image reference paths in the original text must remain unchanged.

4.  **HTML Tags:**
    * If HTML tags are embedded in the original Markdown, these tags and their attributes should also remain unchanged.
    
## III. YAML Frontmatter and Special Comments Handling Requirements

1.  **Format Preservation:**
    * The format of the YAML Frontmatter section at the beginning of the document, surrounded by two '---', must be strictly preserved.
    * Keep all field names, colons, quotes, and other format symbols unchanged.
    
2.  **Field Translation:**
    * Only translate the content values of fields like 'title', 'description', etc.
    * If field values contain quotes, ensure that the quote format is correctly preserved after translation.
    * Do not translate field names, configuration parameter names, or special identifiers.
    
3.  **Special Comments Handling:**
    * Translate the title content in special comments like `[//]: # (title: Content to translate)`.
    * Keep the comment format unchanged, only translate the actual content after the colon.
    * Example: `[//]: # (title: Kotlin/Native as an Apple framework – tutorial)` should be translated to appropriate target language while maintaining the format.

## IV. Output Requirements

1.  **Clean Output:** Output only the translated Markdown content. Do not include any additional explanations, statements, apologies, or self-comments (e.g., "This is a good translation..." or "Please note...").
2.  **Consistent Structure:** Maintain the same document structure and paragraphing as the original text.

---

## V. Resources

### 1. Terminology List (Glossary)
* The following terms must use the specified translations:
No relevant terms

### 2. Reference Translations
* Please refer to the following previously translated document fragments to maintain consistency in style and terminology:
)를 사용하여 해당 변수의 값을 문자열에 삽입합니다:
kotlin
fun main() {
    // Kotlin
    val name = "Joe"
    println("Hello, $name")
    println("Your name is ${name.length} characters long")
}

${name.length}처럼 복잡한 표현식의 값을 중괄호로 감싸서 삽입할 수 있습니다. 자세한 내용은 문자열 템플릿을 참조하세요.

문자열 빌드

Java에서는 StringBuilder를 사용할 수 있습니다:

java
// Java
StringBuilder countDown = new StringBuilder();
for (int i = 5; i > 0; i--) {
    countDown.append(i);
    countDown.append("
");
}
System.out.println(countDown);

Kotlin에서는 문자열을 구성하는 로직을 람다 인수로 받는 인라인 함수buildString()을 사용합니다:

kotlin
fun main() {
       // Kotlin
       val countDown = buildString {
           for (i in 5 downTo 1) {
               append(i)
               appendLine()
           }
       }
       println(countDown)
}

내부적으로 buildString은 Java와 동일한 StringBuilder 클래스를 사용하며, 람다 내부에서 암시적 this를 통해 접근할 수 있습니다.

람다 코딩 컨벤션에 대해 자세히 알아보세요.

컬렉션 항목으로 문자열 생성

Java에서는 항목을 필터링하고, 매핑한 다음 수집하기 위해 Stream API를 사용합니다:

java
// Java
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
String invertedOddNumbers = numbers
        .stream()
        .filter(it -> it % 2 != 0)
        .map(it -> -it)
        .map(Object::toString)
        .collect(Collectors.joining("; "));
System.out.println(invertedOddNumbers);

Kotlin에서는 모든 List에 대해 Kotlin이 정의하는 joinToString() 함수를 사용합니다:

kotlin
fun main() {
    // Kotlin
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val invertedOddNumbers = numbers
        .filter { it % 2 != 0 }
        .joinToString(separator = ";") {"${-it}"}
    println(invertedOddNumbers)
}

Java에서는 구분자와 다음 항목 사이에 공백을 원할 경우 구분자에 명시적으로 공백을 추가해야 합니다.

joinToString() 사용법에 대해 자세히 알아보세요.

문자열이 비어있는 경우 기본값 설정

Java에서는 삼항 연산자를 사용할 수 있습니다:

java
// Java
public void defaultValueIfStringIsBlank() {
    String nameValue = getName();
    String name = nameValue.isBlank() ? "John Doe" : nameValue;
    System.out.println(name);
}

public String getName() {
    Random rand = new Random();
    return rand.nextBoolean() ? "" : "David";
}

Kotlin은 기본값을 인수로 받는 인라인 함수 ifBlank()를 제공합니다:

kotlin
// Kotlin
import kotlin.random.Random

fun main() {
    val name = getName().ifBlank { "John Doe" }
    println(name)
}

fun getName(): String =
    if (Random.nextBoolean()) "" else "David"

문자열의 시작과 끝 문자 바꾸기

Java에서는 replaceAll() 함수를 사용할 수 있습니다. 이 경우 replaceAll() 함수는 각각 ##로 시작하고 끝나는 문자열을 정의하는 정규 표현식 ^####$를 인수로 받습니다:

java
// Java
String input = "##place##holder##";
String result = input.replaceAll("^##|##$", "");
System.out.println(result);

Kotlin에서는 문자열 구분 기호 ##와 함께 removeSurrounding() 함수를 사용합니다:

kotlin
fun main() {
    // Kotlin
    val input = "##place##holder##"
    val result = input.removeSurrounding("##")
    println(result)
}

일치 항목 바꾸기

Java에서는 PatternMatcher 클래스를 사용하여 데이터를 난독화할 수 있습니다:

java
// Java
String input = "login: Pokemon5, password: 1q2w3e4r5t";
Pattern pattern = Pattern.compile("\\w*\\d+\\w*");
Matcher matcher = pattern.matcher(input);
String replacementResult = matcher.replaceAll(it -> "xxx");
System.out.println("Initial input: '" + input + "'");
System.out.println("Anonymized input: '" + replacementResult + "'");

Kotlin에서는 정규 표현식 작업을 단순화하는 Regex 클래스를 사용합니다. 또한, 백슬래시 수를 줄여 정규식 패턴을 단순화하려면 여러 줄 문자열을 사용하세요:

kotlin
fun main() {
    // Kotlin
    val regex = Regex("""\w*\d+\w*""") // multiline string
    val input = "login: Pokemon5, password: 1q2w3e4r5t"
    val replacementResult = regex.replace(input, replacement = "xxx")
    println("Initial input: '$input'")
    println("Anonymized input: '$replacementResult'")
}

문자열 분할

Java에서는 마침표 문자(.)로 문자열을 분할하려면 이스케이프(\\)를 사용해야 합니다. 이는 String 클래스의 split() 함수가 정규 표현식을 인수로 받기 때문입니다:

java
// Java
System.out.println(Arrays.toString("Sometimes.text.should.be.split".split("\\.")));

Kotlin에서는 구분 기호의 가변 인자(varargs)를 입력 매개변수로 받는 Kotlin 함수 split()를 사용합니다:

kotlin
fun main() {
    // Kotlin
    println("Sometimes.text.should.be.split".split("."))
}

정규 표현식으로 분할해야 하는 경우, Regex를 매개변수로 받는 오버로드된 split() 버전을 사용하세요.

부분 문자열 가져오기

Java에서는 부분 문자열을 시작할 문자의 포함 시작 인덱스를 받는 substring() 함수를 사용할 수 있습니다. 이 문자 뒤의 부분 문자열을 가져오려면 인덱스를 증가시켜야 합니다:

java
// Java
String input = "What is the answer to the Ultimate Question of Life, the Universe, and Everything? 42";
String answer = input.substring(input.indexOf("?") + 1);
System.out.println(answer);

Kotlin에서는 substringAfter() 함수를 사용하여 부분 문자열을 가져올 문자의 인덱스를 계산할 필요가 없습니다:

kotlin
fun main() {
    // Kotlin
    val input = "What is the answer to the Ultimate Question of Life, the Universe, and Everything? 42"
    val answer = input.substringAfter("?")
    println(answer)
}

또한, 문자열에서 마지막으로 나타나는 문자 이후의 부분 문자열을 가져올 수 있습니다:

kotlin
fun main() {
    // Kotlin
    val input = "To be, or not to be, that is the question."
    val question = input.substringAfterLast(",")
    println(question)
}

여러 줄 문자열 사용

Java 15 이전에는 여러 줄 문자열을 생성하는 몇 가지 방법이 있었습니다. 예를 들어, String 클래스의 join() 함수를 사용하는 방법이 있습니다:

java
// Java
String lineSeparator = System.getProperty("line.separator");
String result = String.join(lineSeparator,
       "Kotlin",
       "Java");
System.out.println(result);

Java 15에서 텍스트 블록이 도입되었습니다. 한 가지 명심할 점은, 여러 줄 문자열을 출력할 때 세 개의 따옴표(triple-quote)가 다음 줄에 있으면 추가적인 빈 줄이 생긴다는 것입니다:

java
// Java
String result = """
    Kotlin
       Java
    """;
System.out.println(result);

출력 결과:

Java 15 multiline output

마지막 단어와 같은 줄에 세 개의 따옴표(triple-quote)를 두면 이러한 동작 차이는 사라집니다.

Kotlin에서는 따옴표를 새 줄에 배치하여 줄을 포맷할 수 있으며, 출력 결과에 추가적인 빈 줄이 생기지 않습니다. 어떤 줄이든 가장 왼쪽에 있는 문자가 해당 줄의 시작을 나타냅니다. Java와의 차이점은 Java는 자동으로 들여쓰기를 제거하지만, Kotlin에서는 명시적으로 이 작업을 수행해야 한다는 것입니다:

kotlin
fun main() {
    // Kotlin   
    val result = """
        Kotlin
           Java 
    """.trimIndent()
    println(result)
}

출력 결과:

Kotlin multiline output

추가적인 빈 줄을 만들려면 여러 줄 문자열에 해당 빈 줄을 명시적으로 추가해야 합니다.

Kotlin에서는 trimMargin() 함수를 사용하여 들여쓰기를 사용자 지정할 수도 있습니다:

kotlin
// Kotlin
fun main() {
    val result = """
       #  Kotlin
       #  Java
   """.trimMargin("#")
    println(result)
}

여러 줄 문자열에 대해 자세히 알아보세요.

다음 단계는 무엇인가요?

자신이 좋아하는 관용구가 있다면, 풀 리퀘스트를 보내 공유해 주시기 바랍니다.