C# string
In C#, a string is a sequence of Unicode characters. Strings are used to represent text and are one of the most commonly used data types in C#.
To declare a string variable, you can use the string
keyword:
string myString;
To initialize a string with a value, you can use string literals:
string myString = "Hello, world!";
You can also use string interpolation to concatenate strings with values of other data types:
int myInt = 42; string myString = $"The value of myInt is {myInt}";
In this example, the value of myInt
is inserted into the string using the syntax {myInt}
inside the string literal.
Strings in C# are immutable, which means that once a string is created, its contents cannot be changed. However, you can create new strings from existing strings using various string manipulation methods, such as Substring()
, ToLower()
, ToUpper()
, Trim()
, Replace()
, and many others.
Here are some examples of string manipulation methods:
string myString = " Hello, world! "; string trimmedString = myString.Trim(); // removes leading and trailing white space string lowerString = myString.ToLower(); // converts all characters to lowercase string upperString = myString.ToUpper(); // converts all characters to uppercase string replacedString = myString.Replace("world", "everyone"); // replaces "world" with "everyone" string substring = myString.Substring(7, 5); // extracts "world" from the string
In addition to the string
data type, C# also provides a StringBuilder
class that allows you to efficiently build strings by appending or inserting characters or other strings. This can be useful when you need to concatenate a large number of strings or perform frequent modifications to a string.