Arrao4u

…a blog by Rama Rao

Archive for the ‘String Manipulations in c#’ Category

String Manipulations in C#

Posted by arrao4u on January 30, 2010

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

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

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]));

String Concatenation

String concatenation is the act of combining two strings by adding the contents of one string to the end of another. Earlier in this tutorial we considered string operations including using the concatenation operator (+). We used the following example:

string start = "This is a ";
string end = "concatenated string!";

string concat = start + end;    // concat = "This is a concatenated string!"

The String class also provides a method for concatenation of strings. This is the Concat method and it allows many strings to be passed as parameters. These strings are joined together and a new, concatenated string is returned. Note in the example that the Concat method is static and therefore is preceded by the class name, ‘string’. The lower case class name is used as this is C#. However, the .NET framework structure name could be substituted so you may often see String.Concat with a capital ‘S’.

string start = "This is a ";
string end = "concatenated string!";

string concat = string.Concat(start, end);

NB: As with previous string functions, the method returns the concatenated string but the original strings are not modified.

Inserting Strings into Strings

String concatenation is useful when joining two strings end to end. However, the String class also provides a method by which one string can be inserted into the middle of another. This function is useful when using standard template strings that require insertion of text at specific points.

The Insert method acts upon an existing string variable or literal and requires two parameters. The first parameter is an integer that indicates the position where the second string is to be inserted. This integer counts characters from the left with zero indicating that the insertion will be at the beginning of the string. The second parameter is the string to be inserted.

string template = "Please ask for  on arrival.";
string tutor = "Lisa";

Console.WriteLine(template.Insert(15, tutor));

// Outputs: "Please ask for Lisa on arrival."

Removing Characters from a String

The Insert method has an opposite function in the Remove method. This method allows characters to be removed from a string. The characters are simply erased, shortening the string accordingly. There are two overloads available for calling. The first requires a single parameter to indicate the start position for the character removal. The second overload adds a second parameter specifying how many characters to delete. Any further characters are unaffected.

string sample = "The quick brown fox jumps over the lazy dog.";

string result = sample.Remove(16);      // result = "The quick brown "
result = sample.Remove(16, 24);         // result = "The quick brown dog."

Extracting Text from a String

The String class provides a very useful function to extract a piece of text from the middle of an existing string. This method has two overloads that are very similar to those of the Remove method. However, rather than removing the middle section of the string and keeping the start and end, the Substring method discards the start and end and returns the middle section. The following code illustrates this using the same parameters as the previous example.

string sample = "The quick brown fox jumps over the lazy dog.";

string result = sample.Substring(16);   // result = "fox jumps over the lazy dog."
result = sample.Substring(16, 24);      // result = "fox jumps over the lazy "

Search and Replace

All modern word processors and text editors include a search and replace function that permits a specified piece of text to be substituted with a second string. This functionality is actually provided by the .NET framework with the Replace method. The Replace method accepts two parameters. The first is the string to search for and the second is the string to use as a substitute. When executed, all instances of the first parameter string are automatically replaced.

string sample = "The brown fox.";

string result = sample.Replace("brown", "red");   // result = "The red fox."

Copying Strings

The final simple string manipulation function to be considered in this article is the static Copy method. This method simple creates a copy of an existing string. It provides the same functionality as assigning to a string directly.

string sample = "The brown fox.";

string result = string.Copy(sample);    // result = "The brown fox."

Posted in String Manipulations in c# | Leave a Comment »