Visual C# 2005 Guide
String Handling

There are a variety of statements that can be used to manipulate string values. The following properties and methods belong to the string class.

Properties

PropertyDescriptionExample
Chars[x]Returns a char variable equal to the character at position x in the string. (First character is at position 0)char myChar = myString.Chars[3];
LengthReturns an integer equal to the number of characters in the string.int stringLength = myString.Length;

Methods

MethodDescriptionExample
string.Concat(a, b)Concatenates (adds together) the two strings a and b returning a new string.string c = string.Concat(a,b);
Contains(a)Returns true or false depending on whether the string contains the string value specified by the parameter a.bool inString = myString.Contains("@");
IndexOf(a)Returns an integer representing the position of the first occurrence of the string or character a.int pos = myString.IndexOf("@");
LastIndexOf(a)Returns an integer representing the position of the last occurrence of the string or character a.int pos = myString.LastIndexOf("@");
Remove(a)Removes all of the characters of the string beginning at position a and continuing through to the end.string newString = myString.Remove(3);
Remove(a,b)Removes b characters from the string starting at position a.string newString = myString.Remove(3, 2);
Replace(a,b)Replaces all instances of the string a with the string b.string newString = myString.Replace("his", "her");
Substring(a)Returns a substring from the string, starting at position a.string mySub = myString.Substring(3);
Substring(a,b)Returns a substring from the string, starting at position a and continuing for b characters.string mySub = myString.Substring(3, 4);
ToLower()Copies the string to lowercase.string newString = myString.ToLower();
ToUpper()Copies the string to uppercase.string newString = myString.ToUpper();
Trim()Removes white space characters from the start and end of a string.string newString = myString.Trim();
TrimEnd()Removes white space characters from the end of a string.string newString = myString.TrimEnd();
TrimStart()Removes white space characters from the start of the string.string newString = myString.TrimStart();

Having A Go

  1. Read in a string and work out how many characters it contains and then convert the entire string to upper case.
  2. Set a string to the first line of the outrageous ditty below. Search for each of the spaces within the first line and use the Remove method to produce the whole rhyme.

    OH SIR JASPER DO NOT TOUCH ME!
    OH SIR JASPER DO NOT TOUCH!
    OH SIR JASPER DO NOT!
    OH SIR JASPER DO!
    OH SIR JASPER!
    OH SIR!
    OH!
  3. Write a program to read in a word and test if it is a palindrome (reads the same forwards as it does backwards).