Machineboy空

C# - 문자열 함수 및 예제 Split(), Trim(), Substring(), ToLower(), ToUpper(), $문자열 보간, 문자열 검색 IndexOf(), LastIndexOf(),IsNullOrWhiteSpace() 본문

언어/C#

C# - 문자열 함수 및 예제 Split(), Trim(), Substring(), ToLower(), ToUpper(), $문자열 보간, 문자열 검색 IndexOf(), LastIndexOf(),IsNullOrWhiteSpace()

안녕도라 2025. 1. 2. 17:06

문자열 분할(Split()), 문자열 변형(공백 제거, Trim())

형식 [LEVEL]: <MESSAGE>
입력 [Error]: Invalid operation
출력 MESSAGE 부분만
조건 앞, 뒤 공백은 제거 되어야 한다.
// : 기준 문자열 분할
string[] strs = logLine.Split(": ");

// 공백 제거
string message = strs[1].Trim();

 

 

*Split()

https://learn.microsoft.com/ko-kr/dotnet/api/system.string.split?view=net-8.0

 

String.Split 메서드 (System)

지정된 문자열 또는 유니코드 문자 배열의 요소로 구분된 이 인스턴스의 부분 문자열을 포함하는 문자열 배열을 반환합니다.

learn.microsoft.com

 

*Trim()

https://learn.microsoft.com/ko-kr/dotnet/api/system.string.trim?view=net-8.0

 

String.Trim 메서드 (System)

현재 문자열에서 지정된 문자 집합의 선행 및 후행 항목이 모두 제거되는 새 문자열을 반환합니다.

learn.microsoft.com

 

*개행문자

https://etloveguitar.tistory.com/7

 

이스케이프 문자 \r 과 \n은 무엇일까?

이스케이프 문자 이스케이프 문자는 특별한 문자를 입력하기 위해 백슬래쉬(\)를 붙이는 문자를 말한다. 이스케이프 문자들 중 많이 쓰이는 것들은 아래와 같다. \\: 백슬래시 \n: 개행 문자 (라인

etloveguitar.tistory.com


문자열 자르기(SubString()), 문자열 변형(대소문자 변환, ToLower(), ToUpper())

형식 [LEVEL]: <MESSAGE>
입력 [Error]: Invalid operation
출력 LEVEL 부분만
조건 [] 벗기고, 소문자로

 

// []괄호 벗기기
string level = str.Substring(1, strs[0].Length - 2);

// 대문자 -> 소문자 변경
level = level.ToLower();

 


문자열 보간($)

// 문자열 덧셈
return Message(logLine) + " (" + LogLevel(logLine) + ")";

// 문자열 보간 사용
// 기본 형식: $"{함수 혹은 변수 등} 일반 문자열"

return $"{Message(logLine)} ({LogLevel(logLine)})";

 

*문자열 보간

https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/tokens/interpolated

 

$ - 문자열 보간 - 형식 문자열 출력 - C# reference

'$' 토큰을 사용하는 문자열 보간은 기존 문자열 복합 서식 지정보다 문자열 출력의 서식을 지정하는 보다 읽기 쉽고 편리한 구문을 제공합니다.

learn.microsoft.com


문자열 검색 (IndexOf(), LastIndexOf())

using System;

public static class LogAnalysis 
{
    // TODO: define the 'SubstringAfter()' extension method on the `string` type
    public static string SubstringAfter(this string log, string input)
    {
        // Find the index of the delimiter
        int idx = log.IndexOf(input);
        
        // If the delimiter is not found, return an empty string
        if (idx == -1)
        {
            return string.Empty;
        }

        // Return the substring after the delimiter
        return log.Substring(idx + input.Length);
    }

    // TODO: define the 'SubstringBetween()' extension method on the `string` type
    public static string SubstringBetween(this string log, string prefix, string suffix)
    {
        // Find the indexes of the prefix and suffix
        int frontIdx = log.IndexOf(prefix);
        int rearIdx = log.IndexOf(suffix, frontIdx + prefix.Length);

        // If either prefix or suffix is not found, return an empty string
        if (frontIdx == -1 || rearIdx == -1)
        {
            return string.Empty;
        }

        // Extract and return the substring between the prefix and suffix
        return log.Substring(frontIdx + prefix.Length, rearIdx - (frontIdx + prefix.Length));
    }

    // TODO: define the 'Message()' extension method on the `string` type
    public static string Message(this string log)
    {
        return log.SubstringAfter(": ");
    }

    // TODO: define the 'LogLevel()' extension method on the `string` type
    public static string LogLevel(this string log)
    {
        return log.SubstringBetween("[", "]");
    }
}

char, string, array 로 문자열 다루기

// 방법 1: String.Reverse()
using System;
using System.Linq;

public static class ReverseString
{
    public static string Reverse(string input) =>
        new string( input.Reverse().ToArray() );
}


// 방법 2: ToCharArray()
using System;

public static class ReverseString
{
    public static string Reverse(string input)
    {
        char[] a = input.ToCharArray();
        Array.Reverse(a);
        return new string(a);
    }
}

빈 문자열 혹은 공백 체크 (String.IsNullOrWhiteSpace())

https://coding-shop.tistory.com/148