C언어에서 가장 불편한 것을 꼽으라면 문자열 처리가 그중 하나가 된다.


C#에서는 문자열을 쉽고 편리하게 사용할 수 있게 String 이라는 편리한 class를 제공해준다.


그리고 class는 다양한 함수들을 가지고 있는데 잘 사용한다면 문자열들을 다루는데 많은 도움이 된다.


1. Length : 문자열의 길이를 반환 한다.

아래 예제는 abcd def 라는 문자열에 길이인 8을 size 변수에 넣는 것을 알 수 있다.


1
2
3
4
5
string test = "abcd efg";
 
//Length : 글자 길이
int size = test.Length; //8
Console.WriteLine("size : " + size);
cs


출력결과

size : 8




2. Split : 특정 조건으로 문자를 쪼갤 수 있다.

아래 예제는 abcd efg 라는 문자열을 Split(' ') 으로 띄어쓰기 된 부분을 쪼개서 abcd와 efg로 나누는 것을 볼 수 있다.  


1
2
3
4
5
6
string test = "abcd efg";
 
string[] arrTest = test.Split(' '); 
foreach(string str in arrTest) {
    Console.WriteLine(str);
});
cs


출력결과 

abcd

def




3. IndexOf : 특정 문자의 위치를 찾는다. 첫번재 글자는 0을 기준으로 한다.

아래 예제는 abcd efg 문자열에서 Indexof(' ') 해서 공백을 찾아 해당 위치를 반환한다.


1
2
3
4
string test = "abcd efg";
 
int indexSpace = test.IndexOf(' '); //4
Console.WriteLine("index : " + indexSpace);
cs


출력결과

index : 4





4. [index] : 특정 index에 문자를 얻을 수 있다. 0번부터 시작한다.

아래 예제는 abcd efg 에서 index가 1인 b를 반환한다.


1
2
3
4
string test = "abcd efg";
 
char cTest = test[1]; //b
Console.WriteLine("index 1 char : " + cTest);
cs


출력결과

index 1 char : b




5. Substring(시작index, 글자수) : 문자열을 시작 index부터 글자수 만큼 쪼갤 수 있다. 글자수가 없다면 끝까지 쪼갠다.

아래예제는 abcdefghi 라는 문자열을 0번째 index부터 4글자인 abcd를 쪼개서 str1에 넣고 4번째 index부터 4글자인 efgh를 쪼개서 str2에 넣고 7번째 index부터 마지막까지인 hi를 str3에 넣었다.


1
2
3
4
5
6
7
8
9
string test = "abcdefghi";
 
string str1 = test.Substring(04);  //abcd
string str2 = test.Substring(44); //efgh
string str3 = test.Substring(7); //hi
 
Console.WriteLine("str1 : " + str1);
Console.WriteLine("str2 : " + str2);
Console.WriteLine("str3 : " + str3);
cs


출력결과

str1 : abcd

str2 : efgh

str3 : hi




6. StartsWith : 특정 문자로 시작하는지 검사

아래예제는 abcd efg 라는 문자열을 ab로 시작하는지 검사하고 cd로 시작하는지 검사하여 결과를 출력한다.


1
2
3
4
5
6
7
string test = "abcd efg";
 
bool startWith_ab = test.StartsWith("ab"); //True
Console.WriteLine("startWith ab : " + startWith_ab);
 
bool startWith_cd = test.StartsWith("cd"); //False
Console.WriteLine("startWith cd : " + startWith_cd);
cs


출력결과

startWith ab : True

startWith cd : False




7. Contains : 특정 문자열이 포함 되어있는지 검사

아래 예제는 abcd efg 문자열에서 cd가 포함되어있는지와 dc가 포함되어있는지 검사하여 출력한다.


1
2
3
4
5
6
7
string test = "abcd efg";
 
bool contain_cd = test.Contains("cd"); //True
Console.WriteLine("contain cd : " + contain_cd);
 
bool contain_dc = test.Contains("dc"); //False
Console.WriteLine("contain dc : " + contain_dc);
cs


출력결과

contain cd : True

contain dc : False




8. Trim : 앞과 뒤에 빈문자를 제거한다.

아래 예제는 " abcde wef   "의 문자열에 앞뒤에 붙은 문자열을 제거하여 출력한다.


1
2
3
4
string test = " abcde wef   ";
 
string trimStr = test.Trim(); //abc
Console.WriteLine("시작"+trimStr +"끝");
cs


출력결과

시작abcde wef끝

Posted by 꿈만은공돌
,