Tuesday, July 21, 2009

String Manipulation in .Net

To remove specified number of characters from string:

If we want to remove some characters from a string we can remove using Remove function. It will have 2 parameters. First parameter is from where we need to remove and the second parameter is how many characters we need to remove. 2nd parameter is optional

Example:

It will remove 1 to 3 chars “ext” will be removed


string strremove = "Text to remove";
string stremovedtext = strremove.Remove(1, 3);
MessageBox.Show(stremovedtext);

To find a string with in a string:

To check whether a string is with in a string or not. We can use contains to check the speacified string is contains in another string.

Example:

Here we are searching “will” is contained in a text



//to find a text with in a text
string strfind="Text with in myself will be searched";
if (stremovedtext.Contains("will") == true)
{
MessageBox.Show("String found");
}
else
{
MessageBox.Show("String not found");
}

To check the beginning or end of a string

If we want to check the beginning or ending of a string. We can check it by using StartsWith or EndsWith.

Example

Here we want to check the string starts with “text” or ends with “text”



string strstartsorends="Text with in myself will be searched";
if ((strstartsorends.StartsWith("text")) || (strstartsorends.EndsWith("text")))
{
MessageBox.Show("It is started or ended with text");
}
else
{
MessageBox.Show("It is not started or ended with text");
}

1 comment: