C# Strings
In C#, a string is a sequence of characters that represent text.
Strings are reference types and are implemented as instances of the System.String class.
Here are some basic operations you can perform with strings in C#:
Creating a string:
string s1 = "hello";
string s2 = "world";
string s3 = s1 + " " + s2; // s3 is "hello world"
Getting the length of a string:
string s = "hello";
int length = s.Length; // length is 5
Accessing individual characters in a string:
string s = "hello";
char c = s[0]; // c is 'h'
Concatenating strings:
string s1 = "hello";
string s2 = "world";
string s3 = string.Concat(s1, " ", s2); // s3 is "hello world"
Comparing strings:
string s1 = "hello";
string s2 = "world";
bool areEqual = string.Equals(s1, s2); // areEqual is false
Searching for a substring:
string s = "hello world";
int index = s.IndexOf("world"); // index is 6
Replacing a substring:
string s = "hello world";
string newString = s.Replace("world", "everyone"); // newString is "hello everyone"
Splitting a string:
string s = "hello,world";
string[] parts = s.Split(','); // parts is ["hello", "world"]
Converting other types to strings:
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 a string:
You can remove whitespace from the beginning and end of a string using the Trim method, which returns a new string:
string s = " hello world ";
string s2 = s.Trim(); // s2 is "hello world"
ToLower and ToUpper: You can convert a string to lowercase or uppercase using the ToLower and ToUpper methods:
string s = "Hello World";
string s2 = s.ToLower(); // s2 is "hello world"
string s3 = s.ToUpper(); // s3 is "HELLO WORLD"
Note that strings are immutable in C#, which means that you cannot modify an existing string directly.
Instead, you can create a new string that contains the modified content.
'C# > C# Tutorial' 카테고리의 다른 글
C# Arrays and Array.Copy | C# Tutorial for Beginners (0) | 2023.02.14 |
---|---|
C# Boolean | C# Tutorial for Beginners (0) | 2023.02.14 |
C# Nullables | C# Tutorial for Beginners (0) | 2023.02.14 |
C# Operators | C# Tutorial for Beginners (0) | 2023.02.14 |
C# Type Casting | C# Tutorial for Beginners (0) | 2023.02.14 |