본문 바로가기
전공/C# 프로그래밍

3강. 문자열 다루기

by 임 낭 만 2023. 4. 16.

문자열 서식화 및 출력

문자열 서식 맞추기 : Format()

  • string 데이터형의 메소드 (즉, string.Format(⋅))
    • 문자열의 틀을 이용해 서식화된 새로운 문자열 생성
    • 사용 방법은 Console.WriteLine(⋅) 과 동일
    • 첫 번째 매개변수에 “문자열 틀” 입력
    • 두 번째 매개변수부터 문자열 틀 안에 넣을 데이터를 차례로 입력
    • 문자열 틀에 입력하는 {0}, {1} .. 를 “서식항목”이라 칭함

서식 항목의 다양한 서식화

  • 서식 항목의 추가 옵션 구성
    • “서식 항목의 첨자”는 해당 서식항목 위치에 넣을 매개변수 지정
    • “왼쪽/오른쪽 맞춤”은 서식 항목이 차지할 공간의 크기와 공간 안에서 왼쪽 또는 오른쪽에 위치 시킬지 결정
    • “변환 서식 지정 문자열”은 데이터를 지정한 형태로 서식화 (예: 16진수)

왼쪽 / 오른쪽 맞춤

  • 왼쪽 맞춤
    • 서식항목이 차지할 공간의 크기를 나타내는 숫자를 음수로 표현
    • 서식항목을 위한 공간 9칸 생성 후 왼쪽 맞춤 (부호 -)

  • 오른쪽 맞춤

using System;

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

            Console.WriteLine(fmt, "Publisher", "Author", "Title");
            Console.WriteLine(fmt, "Marvel", "Stan Lee", "Iron Man");
            Console.WriteLine(fmt, "Bloomsbury", "J. K. Rowling", "Harry Potter");
            Console.WriteLine(fmt, "T. Egerton", "Jane Austen", "Pride and Prejudice");
        }
    }
}

변환 서식 지정 문자열 : 수 서식화

  • 다양한 형태로 수를 서식화
    • 서식 지정자와 자릿수 지정자(Precision specifier) 동시 사용 가능
    • 예: 서식 문자열 “D5” (서식 지정자: D, 자릿수 지정자: 5)

using System;

namespace StringFormatNumber
{
    class Program
    {
        static void Main(string[] args)
        {            
            // D : 10진수 
            Console.WriteLine("10진수: {0:D}", 123);         // 10진수: 123            
            Console.WriteLine(string.Format("10진수: {0:D}", 123));// 10진수: 123   
            Console.WriteLine("10진수: {0:D5}", 123);         // 10진수: 00123
                                                              // X : 16진수
            Console.WriteLine("16진수: 0x{0:X}", 0xFF1234);   // 16진수: 0xFF1234
            Console.WriteLine("16진수: 0x{0:X8}", 0xFF1234);   // 16진수: 0x00FF1234
                                                              // N : 콤마 구분
            Console.WriteLine("콤마: {0:N}", 123456789);       // 콤마: 123,456,789.00
            Console.WriteLine("콤마: {0:N0}", 123456789);      // 콤마: 123,456,789
                                                               // F : 고정소수점
            Console.WriteLine("고정: {0:F}", 123.45);           // 고정: 123.45
            Console.WriteLine("고정: {0:F5}", 123.456);         // 고정: 123.45600
                                                              // E : 지수 표기
            Console.WriteLine("지수: {0:E}", 123.456789);      // 지수: 1.234568E+002
    }
}

변환 서식 지정 문자열 : 날짜 및 시간 서식화

문화권 별 날짜 및 시간 표기

  • CultureInfo 클래스를 이용해 문화권 정보 표기
    • DateTime.ToString()에 서식 문자열과 이 클래스 객체 입력
    • CultureInfo 생성자에 문화권 이름은 MSDN 참조
using System;
using System.Globalization;

namespace StringFormatDatetime
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = new DateTime(2021, 1, 8, 23, 31, 17);
            
            Console.WriteLine("{0:yyyy-MM-dd tt hh:mm:ss (ddd)}", dt);    // 2021-01-08 오후 11:31:17 (금)            
            Console.WriteLine(dt.ToString("yyyy-MM-dd tt hh:mm:ss (ddd)"));

            CultureInfo ciKo = new CultureInfo("ko-KR");
            Console.WriteLine(dt.ToString("yyyy-MM-dd tt hh:mm:ss (ddd)", ciKo));
            Console.WriteLine(dt.ToString(ciKo));

            CultureInfo ciEn = new CultureInfo("en-US");
            Console.WriteLine(dt.ToString("yyyy-MM-dd tt hh:mm:ss (ddd)", ciEn));
            Console.WriteLine(dt.ToString(ciEn));
        }
    }
}

문자열 서식 맞추기 : 문자열 보간

  • 보간: “비어 있는 부분을 채운다” 의미
    • C# 6.0 부터 지원
    • 서식항목에 첨자 대신 변수이름, 조건식 코드, 상수 등 직접 입력

using System;

namespace StringInterpolation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}, {1}", 123, "가나다");
            Console.WriteLine($"{123}, {"가나다"}"); // 정수와 문자열 입력

            Console.WriteLine("{0,-10:D5}", 123);
            Console.WriteLine($"{123,-10:D5}");     // 맞춤, 서식문자열 사용

            int n = 123;
            string s = "가나다";

            Console.WriteLine("{0}, {1}", n, s);
            Console.WriteLine($"{n}, {s}");         // 변수명 입력

            Console.WriteLine("{0}", n>100?"큼":"작음");
            Console.WriteLine($"{(n > 100 ? "큼" : "작음")}"); // 조건연산자 사용
        }
    }
}


문자열

문자열 안에서 찾기

  • 문자열 안에서 지정된 문자 또는 문자열을 찾는 메소드

using System;

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

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

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

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

            // EndsWith ()
            Console.WriteLine("EndsWith 'Morning' : {0}", greeting.EndsWith("Morning"));
            Console.WriteLine("EndsWith 'M' : {0}", greeting.EndsWith('M'));

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

문자열 변형하기

  • 문자열 변형
    • 문자열 추가 및 삭제
    • 대문자/소문자 변환
    • 문자열 앞/뒤 공백 제거

using System;

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

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

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

문자열 분할하기

using System;

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

            Console.WriteLine(greeting.Substring(0,5));
            Console.WriteLine(greeting.Substring(5));

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

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

'전공 > C# 프로그래밍' 카테고리의 다른 글

5강. 코드 흐름 제어  (0) 2023.04.16
4강. 데이터 가공을 위한 연산자  (1) 2023.04.16
2강. 데이터 타입 (2)  (0) 2023.04.15
2강. 데이터 타입 (1)  (2) 2023.04.14
1강. C# 언어와 .NET 플랫폼 소개  (0) 2023.04.13

댓글