The key thing to remember about C# strings is that they are immutable objects representing text as a sequence of Unicode characters (letters, digits, punctuation, etc.). Double quotes are used to define a string
instance:
string fruit = "Apple";
Manipulating a string can be done by calling one of its methods or properties. As string values can never change after having been defined, all string manipulation methods will return a new string.
A string is delimited by double quote ("
) characters. Some special characters need escaping using the backslash (\
) character. Strings can also be prefixed with the at (@
) symbol, which makes it a verbatim string that will ignore any escaped characters.
string escaped = "c:\\test.txt";
string verbatim = @"c:\test.txt";
escaped == verbatim;
// => true
If you only need a part of a string, you can use the Substring()
method to extract just that part:
string sentence = "Frank chases the bus.";
string name = sentence.Substring(0, 5);
// => "Frank"
The IndexOf
() method can be used to find the index of the first occurence of a string
within a string
, returning -1
if the specified value could not be found:
"continuous-integration".IndexOf("integration")
// => 11
"continuous-integration".IndexOf("deployment")
// => -1
Finally, there are many ways to concatenate a string. The simplest one is by using the +
operator.
string name = "Jane";
"Hello " + name + "!";
// => "Hello Jane!"
For any string formatting more complex than simple concatenation, string interpolation is preferred. To enable interpolation in a string, prefix it with the dollar ($
) symbol.
string name = "Jane";
$"Hello {name}!";
// => "Hello Jane!"