C# Strings
Text can be stored in strings.
A group of characters enclosed in double quotations makes into a string variable:
Example
Make a string-type variable and give it a value:
string greeting = “Hello”;
If desired, a string variable can have a large word count:
Example
string greeting2 = “Nice to meet you!”;
String Length
In C#, a string is actually an object with attributes and methods that may be used to manipulate strings. For instance, the Length property can be used to determine a string’s length:
Example
string txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
Console.WriteLine(“The length of the txt string is: ” + txt.Length);
Other Methods
Example
String Concatenation
Example
You can also use the string.Concat() method to concatenate two strings:
string firstName = “John “;
string lastName = “Doe”;
string name = string.Concat(firstName, lastName);
Console.WriteLine(name);
Adding Numbers and Strings
WARNING!
The + operator is used in C# for both concatenation and addition. Recall that numbers are increased. Concatenated strings are used.
A number is the outcome of adding two numbers:
Example
int x = 10;
int y = 20;
int z = x + y;
Console.WriteLine(z);
A string concatenation is produced when two strings are added:
Example
String Interpolation
Example
Access Strings
Example
Note that the first string index is 0: The initial character is [0]. The second character is [1], and so on.
The second character (1) in myString is printed in this example:
Example
Example
Strings – Special Characters
Due to the requirement that strings be put inside quotes, C# will interpret this string incorrectly and produce an error:Escape character | Result | Description |
---|---|---|
\’ | ‘ | Single quote |
\” | “ | Double quote |
\\ | \ | Backslash |
ExampleGet
string txt = “We are the so-called \”Vikings\” from the north.”; A single quote is inserted into a string using the sequence \’:Example
string txt = “It\’s alright.” A single backslash is inserted into a string via the sequence \\:Example
Code | Result |
---|---|
\n | New Line |
\t | Tab |
\b | Backspace |