String Manipulation

Your use of strings so far has consisted of writing strings to the console, reading strings from the console, and concatenating strings using the + operator. In the course of programming more interesting applications, you will soon discover that manipulating strings is something that you end up doing a lot . Because of this, it is worth spending a few pages looking at some of the more common string manipulation techniques available in C#.
To start with, note that a string type variable can be treated as a read – only array of char variables. This means that you can access individual characters using syntax like the following:

string myString = "A string";
char myChar = myString[1];

However, you can ’ t assign individual characters in this way. To get a char array that you can write to, you can use the following code. This uses the ToCharArray() command of the array variable:

string myString = "A string";
char[] myChars = myString.ToCharArray();

Then you can manipulate the char array in the standard way. You can also use strings in foreach loops, as shown here:

foreach (char character in myString)
Console.WriteLine("{0}", character);

As with arrays, you can also get the number of elements using myString.Length . This gives you the number of characters in the string:

string myString = Console.ReadLine();
Console.WriteLine("You typed {0} characters.", myString.Length);

You may also like...