C#/C# 강좌

C# 강좌 - 문자열 (String)

DragonTory 2023. 2. 19. 11:52
반응형

C# 강좌 - 문자열 (String)

  
C#에서 문자열은 텍스트를 나타내는 일련의 문자입니다.

문자열은 참조 타입이며 System.String 클래스의 인스턴스로 구현됩니다.

다음은 C#에서 문자열로 수행할 수 있는 몇 가지 기본 작업입니다.



문자열 만들기:

string s1 = "hello";
string s2 = "world";
string s3 = s1 + " " + s2; // s3 is "hello world"


문자열 길이 구하기: Length

string s = "hello";
int length = s.Length; // length is 5


문자열의 개별 문자에 액세스:

string s = "hello";
char c = s[0]; // c is 'h'

  
문자열 연결: Concat

string s1 = "hello";
string s2 = "world";
string s3 = string.Concat(s1, " ", s2); // s3 is "hello world"



문자열 비교: Equals

string s1 = "hello";
string s2 = "world";
bool areEqual = string.Equals(s1, s2); // areEqual is false


문자열 검색: IndexOf

string s = "hello world";
int index = s.IndexOf("world"); // index is 6

 

문자열 바꾸기:

string s = "hello world";
string newString = s.Replace("world", "everyone"); // newString is "hello everyone"


문자열 분할: Split

string s = "hello,world";
string[] parts = s.Split(','); // parts is ["hello", "world"]


다른 타입을 문자열로 변환: ToString

int i = 10;
string s = i.ToString(); // s is "10"
double d = 3.14;
string s = d.ToString("F2"); // s is "3.14"
bool b = true;
string s = b.ToString(); // s is "True"

 

문자열 공백 자르기: Trim

새 문자열을 반환하는 Trim 메서드를 사용하여 문자열의 시작과 끝에서 공백을 제거할 수 있습니다.

string s = "  hello world   ";
string s2 = s.Trim(); // s2 is "hello world"

  

대 소문자 변환: ToLower, ToUpper

ToLower 및 ToUpper 메서드를 사용하여 문자열을 소문자 또는 대문자로 변환할 수 있습니다.

string s = "Hello World";
string s2 = s.ToLower(); // s2 is "hello world"
string s3 = s.ToUpper(); // s3 is "HELLO WORLD"



C#에서 문자열은 직접 변수 내용을 변경할 수 없으므로 기존 문자열을 직접 수정할 수 없습니다.

대신 수정된 내용을 포함하는 새 문자열을 만들 수 있습니다.

다른 방법으로는 StringBuilder 객체를 사용 할 수 있습니다.

StringBuilder 를 사용 하면 문자열 값을 변경 할 수 있습니다.

string input = "The quick brown fox jumps over the lazy dog";
StringBuilder sb = new StringBuilder();

// Read the input string one word at a time, appending each word to the StringBuilder
string[] words = input.Split(' ');
foreach (string word in words)
{
	sb.Append(word);
	sb.Append(' ');
}

// Replace the word "fox" with "dog"
int startIndex = sb.ToString().IndexOf("fox");
sb.Replace("fox", "dog", startIndex, "fox".Length);

string output = sb.ToString();
Console.WriteLine(output);
반응형