Search:

Custom Search
_________________________________________________________________

Monday, March 17, 2008

String Manipulation (C#)

Here I will show you some useful string manipulation functions in C#.


ToUpper, ToLower function.


Coverts all the characters from a String into upper/lower case. Example:

String st = " String Manipulation in C# ";
String a3 = st.ToUpper();


Trim function.


The trim function strips all white spaces form both start and end form a given string. It has two other variants, the TrimStart and TrimEnd.

Example:

String trimed = st.Trim();

Console.WriteLine("Original: " + st);
Console.WriteLine("Using Trim: " + "=" + trimed +"=");

String trimedStart = st.TrimStart();
Console.WriteLine("1st TrimStart: " + trimedStart + "=");

//Other TrimStart variant
char[] c = { ' ', 'S' };
String trimedStart2 = st.TrimStart(c);
Console.WriteLine("2nd TrimStart: " + trimedStart2 + "=");


ToReplace function.


The ToReplace function searches for a string/char to be replaced with a new string/char value. Example:

String toRepalce = st.Replace("C#" , "Java");
Console.WriteLine("=" + toRepalce + "=");

Split Function


Useful function when you want to split a string using delimiter. Example:

String [] a = st.Split('g');
String first = a[0];
String second = a[1];
Console.WriteLine("=" + first + "=");
Console.WriteLine("=" + second + "=");


Remove function.


The Remove function lets you strip a specified number of characters. The first value you set indicates the starting point and the second the total characters to strip. Example:

String a2 = st.Remove(10, 13);
Console.WriteLine("=" + a2 + "=");

Substring Function.

Removes a certain amount of characters form the 0 of the string to the used position. Example:

String a1 = st.Substring(9);
Console.WriteLine("=" + a1 + "=");

No comments: