AllTheTimeWorld.com

csharp stringsString Functions

String Functions

Examples of the most used string methods

String Functions

Examples of the most used string methods

The String class includes many methods for handling the string. Look at the examples below and try them one at a time:

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
this.Text = alphabet.ToLower(); // abcdefghijklmnopqrstuvwxyz
this.Text = "" + alphabet.Length; // 26
this.Text = alphabet.Substring(0, 3); // ABC
this.Text = alphabet.Substring(5, 2); // FG
this.Text = alphabet.Substring(20); // UVWXYZ
this.Text = ""+ alphabet.IndexOf("D"); // 3
this.Text = "" + alphabet.IndexOf("XYZ"); // 23
this.Text = "" + alphabet.IndexOf("xyz"); // -1 "xyz" is not found
this.Text = "" + alphabet.StartsWith("A"); // True
this.Text = "" + alphabet.StartsWith("ABC"); // True
this.Text = "" + alphabet.StartsWith("AC"); // False
this.Text = "" + alphabet.Replace("A", "*"); // *BCDEFGHIJKLMNOPQRSTUVWXYZ
this.Text = "" + alphabet.Contains("DEF"); // True

String sentence = "A man and a woman manage the store.";
this.Text = "" + sentence.LastIndexOf("man"); // 18    (in manage)
this.Text = "" + sentence.Replace("man", "person"); //A person and a woperson personage the store.
String[] words = sentence.Split(' ');
this.Text = "" + words.Length; // 8
this.Text = words[0]; // A
this.Text = words[1]; // man
this.Text = words[2]; // and
this.Text = words[words.Length-1]; // store.   Note: the period is part of last word.

Like arrays, the index on Strings begins with 0.
The Length() of Alphabet is 26, there are 26 letters with A in position 0 and Z in position 25.
We can combine these functions in various ways.

Experiment: Try some of these string functions.