Changes

Jump to: navigation, search

Working with Strings in C Sharp

2,492 bytes added, 20:49, 23 January 2008
Comparing Strings in C#
System.Console.WriteLine ("They do not match");
}
</pre>
 
== Changing String Case ==
 
The case of the characters in a string may be changed using the ToUpper and ToLower methods. Both of these methods return a modified string rather than changing the actual string. For example:
 
<pre>
string myString = "Hello World";
string newString;
 
newString = myString.ToUpper();
 
System.Console.WriteLine (newString); // Displays HELLO WORLD
 
newString = myString.ToLower();
 
System.Console.WriteLine (newString); // Displays hello world
</pre>
 
== Splitting a C# String into Multiple Parts ==
 
A string may be separated into multiple parts using the ''Split()'' method. Split() takes as an argument the character to use as the delimiter to identify the points at which the string is to be split. Returned from the method call is an array containing the individual parts of the string. For example, the following code splits a string up using the comma character as the delimiter. the results are placed in an array called ''myColors'' and a foreach loop then reads each item from the array and displays it:
 
<pre>
string myString = "Red, Green, Blue, Yellow, Pink, Purple";
 
string[] myColors = myString.Split(',');
 
foreach (string color in myColors)
{
System.Console.WriteLine (color);
}
</pre>
 
The resulting output will read:
 
<pre>
Red
Green
Blue
Yellow
Pink
Purple
</pre>
 
As we can see, the ''Split()'' method broke the string up as requested, by we have a problem in that the spaces are still present. Fortunately C# provides a method to handle this.
 
== Trimming and Padding C# Strings ==
 
Unwanted leading and trailing spaces can be removed from a string using the ''Trim()'' method. When called, this method returns a modified version of the string:
 
<pre>
string myString = " hello ";
 
System.Console.WriteLine ("[" + myString + "]");
System.Console.WriteLine ("[" + myString.Trim() + "]");
</pre>
 
The above code will result in the following output:
 
<pre>
[ hello ]
[hello]
</pre>
 
In inverse of the ''Trim()'' method are the ''PadLeft()'' and ''PadRight()'' methods. These methods allow leading or trailing characters to be added to a string. The methods take as arguments the total number of characters to which the string is to be padded and the padding character:
 
<pre>
string myString = "hello";
string newString;
 
newString = myString.PadLeft(10, ' ');
 
newString = newString.PadRight(20, '*');
 
System.Console.WriteLine ("[" + newString + "]"); // Outputs [ hello**********]
</pre>

Navigation menu