Google
 

Sunday, March 14, 2010

Programming String Manipulation in C#

Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimEnd

TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

//STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimStart

TrimStart is the same as TrimEnd apart from it does it to the start of the string.

//STRIPS CHRS FROM THE START OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','S'};
string NewName = Name.TrimStart(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

Find String within string

This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
//SHOWS START POSITION OF STRING
MessageBox.Show("Found at : " + FirstChr );

Replace string in string

Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString "String Manipulatin";
string CorrectString = MainString.Replace("Manipulatin", "Manipulation");
//SHOW CORRECT STRING
MessageBox.Show("Correct string is : " + CorrectString);

Strip specified number of characters from string

This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = "S1111tring Manipulation";
string NewString = MainString.Remove(1,4);

//SHOW OUTPUT
MessageBox.Show(NewSring);

Split string with dilemeter

The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = "String Manipulation";
string [] Split = MainString.Split(new Char [] {' '});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));