Strings
String is a class. It allows us to store some text. But it also gives us some useful functions to help us get part of the some text, or compare two words, or find a word.
Create a String
Here is a string variable. It is initialised with "Hello World"
String Greeting = "Hello World";
Substring - Get part of a string
String Greeting = "Hello World";
FirstWord
is assigned the first five letters of Greeting. SubString()
starts at the beginning includes 5 letters. FirstWord
therefore contains the word "Hello"
String FirstWord = Greeting.Substring(0, 5);
SecondWord
is assigned five letters from Greeting starting at array position 6. It includes the next 5 letters. SecondWord
therefore contains the word "World"
String SecondWord = Greeting.Substring(6, 5);
Console.WriteLine(FirstWord);
Console.WriteLine(SecondWord);
Output:
Hello
World
If you use SubString()
with one value, it will start at that value and include the rest of the text
String SecondWord = Greeting.Substring(2);
Output:
llo World
indexOf - Find the position of the first occurence of a given letter (or word) in the string.
int pos = str.indexOf("b");
pos
will be 1.
Note: If the letter or word is not found, the method will return -1.
You can use a string like an array
A string is stored as an array of single letters (chars). Therefore you can refer to each letter separately as you would an item in an array:
string message = "Hello";
Console.WriteLine(message[0])
The code above would output "H"
as this is the letter stored at position 0.