C#

[C#] 문자열(string) 메소드 종류 및 예시

homoon 2023. 5. 20. 18:38

1. 문자열 찾기

- IndexOf()     - 현재 문자열 내에서 찾고자 하는 지정된 문자 또는 문자열의 위치를 찾습니다.
- LastIndexOf() - 현재 문자열 내에서 찾고자 하는 지정된 문자 또는 문자열의 위치를 뒤에서부터 찾습니다.
- StartsWith()  - 현재 문자열이 지정된 문자열로 시작하는지를 평가합니다.
- EndsWith()    - 현재 문자열이 지정된 문자열로 끝나는지를 평가합니다.
- Contains()    - 현재 문자열이 지정된 문자열을 포함하는지를 평가 합니다.
- Replace()     - 현재 문자열에서 지정된 문자열이 다른 문자열로 모두 바뀐 새 문자열을 반환합니다.

using static System.Console;

namespace StringSearch
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string greeting = "Good Morning";

            WriteLine(greeting);
            WriteLine();

            // indexOf()
            WriteLine("IndexOf 'Good' : {0}", greeting.IndexOf("Good"));                // 0
            WriteLine("IndexOf 'o' : {0}", greeting.IndexOf('o'));                      // 1

            // LastIndexOf()
            WriteLine("LastIndexOf 'Good' : {0}", greeting.LastIndexOf("Good"));        // 0
            WriteLine("LastIndexOf 'o' : {0}", greeting.LastIndexOf('o'));              // 6

            // StartsWith()
            WriteLine("StartsWith 'Good' : {0}", greeting.StartsWith("Good"));          // True
            WriteLine("StartsWith 'Morning' : {0}", greeting.StartsWith("Morning"));    // False

            // EndsWith()
            WriteLine("EndsWith 'Good' : {0}", greeting.EndsWith("Good"));              // False
            WriteLine("EndsWith 'Morning' : {0}", greeting.EndsWith("Morning"));        // True

            // Contains()
            WriteLine("Contains 'Evening' : {0}", greeting.Contains("Evening"));        // False
            WriteLine("Contains 'Morning' : {0}", greeting.Contains("Morning"));        // True

            // Replace()
            WriteLine("Replaced 'Morning' with 'Evening' : {0}",
                greeting.Replace("Morning", "Evening"));                                // Good Evening
        }
    }
}

2. 문자열 수정

- ToLower()     : 현재 문자열의 모든 대문자를 소문자로 바꾼 새 문자열을 반환합니다.
- ToUpper()     : 현재 문자열의 모둔 소문자를 대문자로 바꾼 새 문자열을 반환합니다.
- Insert()      : 현재 문자열의 지정된 위치에 지정된 문자열이 삽입된 새 문자열을 반환합니다.
- Remove()      : 현재 문자열의 지정된 위치로부터 지정된 수만큼의 무자가 삭제된 새 문자열을 반환합니다.
- Trim()        : 현재 문자열의 앞/뒤에 있는 공백을 삭제한 새 문자열을 반환합니다.
- TrimStart()   : 현재 문자열의 앞에 있는 공백을 삭제한 새 문자열을 반환합니다.
- TrimEnd()     : 현재 문자열의 뒤에 있는 공백을 삭제한 새 문자열을 반환합니다.

using static System.Console;

namespace StringModify
{
    internal class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Lower() : '{0}'", "ABC".ToLower());                      // 'abc'
            WriteLine("ToUpper() : '{0}'", "ABC".ToUpper());                    // 'ABC'

            WriteLine("Insert() : '{0}'", "Happy Friday!".Insert(5, " Sunny")); // 'Happy Sunny Friday!'
            WriteLine("Remove() : '{0}'", "I Don't Love You".Remove(2, 6));     // 'I Love You'

            WriteLine("Trim() : '{0}'", " No Spaces ".Trim());                  // 'No Spaces'
            WriteLine("TrimStart() : '{0}'", " No Spaces ".TrimStart());        // 'No Spaces '
            WriteLine("TrimEnd() : '{0}'", " No Spaces ".TrimEnd());            // ' No Spaces'
        }
    }
}

3. 문자열 분할

   - Split()       - 현재 문자열을 지정된 문자를 기준으로 분리한 문자열의 배열을 반환합니다.
   - SubString()   - 현재 문자열을 지정된 위치로부터 지정된 수만큼의 문자로 이루어진 새 문자열을 반환합니다.

namespace StringSlice
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string greeting = "Good morning.";

            Console.WriteLine(greeting.Substring(0, 5));    // Good
            Console.WriteLine(greeting.Substring(5));       // morning.
            Console.WriteLine();

            string[] arr = greeting.Split(
                new string[] {" "}, StringSplitOptions.None
                );
            Console.WriteLine("Word Count : {0}", arr.Length);  // Word Count : 2

            foreach (string element in arr)
            {
                Console.WriteLine("{0}", element);
            }
            // Good
            // morning.
        }
    }
}

4. format() 메소드

 - 4-1. 왼쪽/오른쪽 맞춤

using static System.Console

// 예시 코드
namespace StringFormatBasic
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string fmt = "{0,-20}{1,-15}{2, 30}";

            WriteLine(fmt, "Publisher", "Author", "Title");
            WriteLine(fmt, "Marvel", "Stan Lee", "Iron Man");
            WriteLine(fmt, "Hanbit", "Sanghyun", "C# 7.0 Programming");
            WriteLine(fmt, "Prentice Hail", "K&R", "The C# Programming Language");
        }
    }
}

 - 4-2. 숫자 서식화

using static System.Console;

namespace StringFormatNumber
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // D : 10진수
            WriteLine("10진수 : {0:D}", 123); // 123
            WriteLine("10진수 : {0:D5}", 123); // 00123

            // X : 16진수
            WriteLine("16진수 : 0x{0:X}", 0xFF1234); // 0xFF1234
            WriteLine("16진수 : 0x{0:X8}", 0xFF1234); // 0x00FF1234

            // N : 숫자
            WriteLine("숫자 : {0:N}", 123456789); // 123,456,789.00
            WriteLine("숫자 : {0:N0}", 123456789); // 자릿수 0은 소숫점 이하를 제거함 // 123,456,789

            // F : 고정소수점
            WriteLine("고정소수점 : {0:F}", 123.45); // 123.45
            WriteLine("고정소수점 : {0:F5}", 123.456); // 123.45600

            // E : 공학용
            WriteLine("공학 : {0:E}", 123.456789); // 1.2345678E+002
        }
    }
}

 - 4-3. 날짜 및 시간 서식화

using System.Globalization;
using static System.Console;

/*
 * - 서식 지정자(MSDN)
 *  y   : 연도       : yy(두자리수 연도), yyyy(네 자릿수 연도)
 *  M   : 월         : M(한 자릿수 월), MM(두 자릿수 월)
 *  d   : 일         : d(한자릿수 일), dd
 *  h   : 시(1~12)   : h, hh
 *  H   : 시(1~23)   : H, HH
 *  m   : 분         : m, mm
 *  s   : 초         : s, ss
 *  tt  : 오전/오후  : tt
 *  ddd : 요일       : ddd(약식 요일), dddd(전체 요일)
 */
namespace StringFormatDatetime
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = new DateTime(2023, 05, 26, 14, 54, 38);

            WriteLine("12시간 형식 : {0:yyyy-MM-dd tt hh:mm:ss (ddd)}", dt); // 12시간 형식 : 2023-05-26 오후 02:54:38 (금)
            WriteLine("24시간 형식 : {0:yyyy-MM-dd HH:mm:ss (dddd)}", dt); // 24시간 형식 : 2023-05-26 14:54:38 (금요일)

            CultureInfo ciKo = new CultureInfo("ko-KR");
            WriteLine();
            WriteLine(dt.ToString("yyyy-MM-dd tt hh:mm:ss (ddd)}", ciKo)); // 2023-05-26 오후 02:54:38 (금)}
            WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss (dddd)}", ciKo)); // 2023-05-26 14:54:38 (금요일)}
            WriteLine(dt.ToString(ciKo)); // 2023-05-26 오후 2:54:38

            CultureInfo ciEn = new CultureInfo("en-US");
            WriteLine();
            WriteLine(dt.ToString("yyyy-MM-dd tt hh:mm:ss (ddd)}", ciEn)); // 2023-05-26 PM 02:54:38 (Fri)}
            WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss (dddd)}", ciEn)); // 2023-05-26 14:54:38 (Friday)}
            WriteLine(dt.ToString(ciEn)); // 5/26/2023 2:54:38 PM
        }
    }
}

5. 문자열 보간

using static System.Console;

namespace StringInterpolation
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string name = "김튼튼";
            int age = 23;
            WriteLine($"{name,-10}, {age:D3}");

            name = "박날씬";
            age = 30;
            WriteLine($"{name}, {age,-10:D3}");

            name = "이비실";
            age = 17;
            WriteLine($"{name}, {(age > 20 ? "성인" : "미성년자")}");
        }
    }
}