부록A. 문자열 다루기

2020. 1. 7. 19:50C# 언어/이것이 C# 이다. 책정리

반응형

부록 A '문자열 다루기' 입니다

string형식의 문자열을 가공하고 다양한 기능을 배웁니다!

 

'이것이 C#이다' 교재를 바탕으로 정리했습니다.

 

이전 정리글

 


ㅇ string 형식 메소드

 

문자열 안에서 찾기

 

메소드 설명 반환
indexOf() 지정 문자,문자열 위치 찾음 int형
LastIndexOf() 지정 문자,문자열을 뒤에서 부터 찾음 int형
StartWith() 지정 문자로 시작하는지 평가 true/false or -1
EndsWith() 지정 문자로 끝나는지 평가 true/false or -1
Contains() 지정 문자를 포함하는지 평가 true/false or -1
Replace() 문자열 교체  

 

표에 언급한 모든 메소드 이용한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using static System.Console;
 
 
namespace StringSearch
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string greeting = "Good Morning";
            
            WriteLine(greeting);
            WriteLine();
 
            // IndexOf()
            WriteLine("Index 'Good' : {0}",greeting.IndexOf("Good")); // 0
            WriteLine("Index 'o' : {0}", greeting.IndexOf("o")); // 1
            var a = greeting.IndexOf("g"); 
            WriteLine(a.GetType()); // Systme.Int32
 
 
            // 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.EndsWith("Evening")); // False
            WriteLine("Contains 'Morning' : {0}", greeting.EndsWith("Morning")); // True
 
            // Replace()
            WriteLine("Replaced 'Morning' with 'Evening' : {0}", greeting.Replace("Morning","Evening")); // Good Evening
 
        }
    }
}

 

 
문자열 변형하기

 

메소드 설명
ToLower() 모든 대문자를 소문자로 변환
ToUpper() 모든 소문자를 대문자로 변환
Insert() 지정된 위치에 지정된 문자열 삽입
Remove() 지정된 위치로 부터 지정된 수만큼 문자열 삭제
Trim() 현재 문자열의 앞/뒤 공백 삭제
TrimStart() 현재 문자열의 앞에 있는 공백 삭제
TrimEnd() 현재 문자열의 뒤에 있는 공백 삭제

 

표에 언급한 모든 메소드 이용한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using static System.Console;
 
namespace StringModify
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("ToLower() : '{0}'""ABC".ToLower()); // 'abc'
            WriteLine("ToLower() : '{0}'""abc".ToUpper()); // 'ABC'
 
            WriteLine("Insert() : '{0}'""Happy Friday!".Insert(5" Sunny")); // 'Happy Sunny Friday!'
            WriteLine("Romove() : '{0}'""I Don`t Love You.".Remove(26)); // 'I Love You'
 
            WriteLine("Trim() : '{0}'"" No Spaces ".Trim()); // 'No Spaces'
            WriteLine("Trim() : '{0}'"" No Spaces ".TrimStart()); // 'No Spaces '
            WriteLine("Trim() : '{0}'"" No Spaces ".TrimEnd()); // ' No Spaces'
 
        }
    }
}

 

문자열 분할하기

 

메소드 설명
Split() 현재 문자열을 지정된 문자를 기준으로 분리한 문자열의 배열을 반환
SubString() 현재 문자열을 지정된 위치로부터 지정된 수 만큼 변환 

 

표에 언급한 모든 메소드 이용한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using static System.Console;
 
namespace StringSlice
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string greeting = "Good morning.";
 
            WriteLine(greeting.Substring(05)); // "Good"
            WriteLine(greeting.Substring(5)); // "morning"
            WriteLine();
 
            string[] arr = greeting.Split(
                new string[] { " " },StringSplitOptions.None);
 
            WriteLine("Word Count : {0}"arr.Length); // Word Count : 2
 
            foreach (string elemnet in arr)
                WriteLine("{0}", elemnet); // Good
                                            // morning
        }
    }
}

* foreach문은 이후에..


 

ㅇ 문자열 서식 맞추기

C#은 문자열 서식화에 사용할 수 있는 간편한 방법 두 가지를 제공합니다.

첫 번째는 string 형식의 format() 메소드

두 번째는 문자열 보간 방법

 

Format() 형식

 

Console.WriteLine("Total : { 0, -7: D}", 123); // 첨자 : 0, 맞춤 : -7, 서식 문자열 : D

 

  • 왼쪽/ 오른쪽 맞춤
맞춤 없음
string result = string.Format("{0}DEF", "ABC");
// result = "ABCDEF"

왼쪽 맞춤
string result = string.Format("{0,-10}DEF", "ABC");
// result = "ABC       DEF"

오른쪽 맞춤
string result = string.Format("{0,10}DEF", "ABC");
// result = "       ABCDEF"

예제 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using static System.Console;
 
namespace StringFormatBasic
{
    class MainApp
    {
        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, "Hanvit""Sanghyun Park""C# 7.0 Programming");
            WriteLine(fmt, "Prentice Hall""K&R""The C Programming Language");
 
        }
    }
}
출력값

 

문자열 보간

문자열 보간은 C# 6.0에서 새로 도입된 기능, 한결 더 편리하게 문자열의 양식을 맞출 수 있도록 도와줌

string.Format() 문자열 보간
WriteLine("{0},{1}", 123,"C#공부"); WriteLine($"{123},{"C#공부"}");
WrinteLine("{0,-10,D5}", 123); WrinteLine($"{123,-10,:D5);

int n = 123;

string s = "c#공부";

WriteLine("{0}{1}",n,s);

int n = 123;

string s = "c#공부";

WriteLine($"{n},{s}");

int n = 123;

WriteLine("{0}",n > 100? "큼" : "작음");

int n = 123;

WriteLine($"{(n>100? "큼":"작음")}");

 

반응형