Contents
접기
728x90
문자열이란?
문자들의 모음! "안녕", "Hello" 같은 것이다.
C#에선 string 자료형을 사용한다.
연결(+, String.Concat(), $"")
string a = "Hello";
string b = "World";
string result = a + " " + b; // Hello World
📌 변수끼리 +로 붙일 수 있다.
분할(Split)
string text = "사과,바나나,포도";
string[] fruits = text.Split(',');
Console.WriteLine(fruits[1]); // 바나나
📌 구분자를 기준으로 나눠 배열로 저장한다.(여기서는 ","로구분)
검색(Contains, IndexOf, StartsWith, EndsWith)
string word = "pineapple";
Console.WriteLine(word.Contains("apple")); // true
Console.WriteLine(word.IndexOf("p")); // 0
Console.WriteLine(word.StartsWith("pine")); // true
Console.WriteLine(word.EndsWith("e")); // true
📌 어떤 단어가 포함되어 있는지, 어디에 있는지 확인할 수 있다.
대체(Replace)
string text = "나는 배고파요";
string result = text.Replace("배고파요", "배불러요");
Console.WriteLine(result); // 나는 배불러요
📌 특정 단어를 다른 단어로 바꿀 수 있다.
변환(ToUpper(), ToLower(), Trim())
string name = " Apple ";
Console.WriteLine(name.ToUpper()); // " APPLE "
Console.WriteLine(name.ToLower()); // " apple "
Console.WriteLine(name.Trim()); // "Apple"
📌 대소문자 바꾸기, 공백 제거등을 할 수 있다.
문자열 값 비교(==, Equals)
string a = "hi";
string b = "hi";
Console.WriteLine(a == b); // true
Console.WriteLine(a.Equals(b)); // true
📌 같은 값을 가지고 있는지 비교할 수 있다.
문자열 대소비교(CompareTo, String.Compare)
Console.WriteLine("apple".CompareTo("banana")); // 음수 (앞에 있음)
Console.WriteLine("banana".CompareTo("apple")); // 양수 (뒤에 있음)
📌 사전 순으로 앞/뒤/같음 비교가 가능하다.
문자열 포멧팅
문자열 형식화 (String.Format)
string name = "철수";
int age = 10;
string result = String.Format("{0}는 {1}살입니다.", name, age);
Console.WriteLine(result); // 철수는 10살입니다.
문자열 보간 ($)
string name = "영희";
int score = 100;
Console.WriteLine($"{name}의 점수는 {score}점입니다.");
📌 $ 보간이 더 간단해서 많이 쓴다.
728x90
'C# > 데이터다루기' 카테고리의 다른 글
| [C#] C#에서 new()만 써도 된다? (0) | 2025.05.20 |
|---|---|
| [C#] 열거형(enum) (0) | 2025.04.24 |
| [C#] 리터럴(literal) (0) | 2025.04.14 |
| [C#] Escape Sequence (0) | 2025.04.14 |
| [C#] Console.ReadLine(), Console.WriteLine(), Console.Read(), Console.Write() (0) | 2025.03.20 |