상세 컨텐츠

본문 제목

문자열

C#

by 메타 스토리 2023. 9. 5. 01:52

본문

using System;

class Program
{
    static void Main()
    {
        // 1. 문자열 생성
        string str1 = "Hello, ";
        string str2 = "world!";

        // 2. 문자열 연결
        string result = str1 + str2; // Concatenation: Hello, world!

        // 3. 문자열 길이
        int length = result.Length; // Length: 13

        // 4. 대소문자 변환
        string upperCase = result.ToUpper(); // UpperCase: HELLO, WORLD!
        string lowerCase = result.ToLower(); // LowerCase: hello, world!

        // 5. 문자열 비교
        bool isEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // Equality: False

        // 6. 문자열 검색
        bool contains = result.Contains("world"); // Contains 'world': True
        int indexOf = result.IndexOf("world"); // Index of 'world': 7
        int lastIndex = result.LastIndexOf("world"); // Last Index of 'world': 7

        // 7. 문자열 잘라내기
        string substring = result.Substring(0, 5); // Substring: Hello

        // 8. 문자열 대체
        string replaced = result.Replace("world", "universe"); // Replacement: Hello, universe!

        // 9. 문자열 나누기
        string[] words = result.Split(' ');
        // Split:
        // Hello,
        // world!

        // 10. 문자열 형식화
        int number = 42;
        string formatted = string.Format("The answer is {0}", number); // Formatted: The answer is 42

        // 결과 출력
        Console.WriteLine("Concatenation: " + result);
        Console.WriteLine("Length: " + length);
        Console.WriteLine("UpperCase: " + upperCase);
        Console.WriteLine("LowerCase: " + lowerCase);
        Console.WriteLine("Equality: " + isEqual);
        Console.WriteLine("Contains 'world': " + contains);
        Console.WriteLine("Index of 'world': " + indexOf);
        Console.WriteLine("Last Index of 'world': " + lastIndex);
        Console.WriteLine("Substring: " + substring);
        Console.WriteLine("Replacement: " + replaced);
        Console.WriteLine("Split:");
        foreach (var word in words)
        {
            Console.WriteLine(word);
        }
        Console.WriteLine("Formatted: " + formatted);
    }
}

'C#' 카테고리의 다른 글

Stack  (0) 2023.09.05
Queue  (0) 2023.09.05
List  (0) 2023.09.05
string.Format  (0) 2023.09.05
Path  (0) 2023.09.04

관련글 더보기