Monday, November 15, 2010

String Manipulation in .NET

String is one of the most frequently used data types in programming. There are quite a few string functions out there and all of those functions are implemented differently in different programming languages. I am going to show here how this is done in .NET Framework.
In the example below I am going to demonstrate the use of StringBuilder class. The below example receives a string as a parameter and then reverses it:
private string ReverseString(String str)
{
    if (str != string.Empty)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = str.Length - 1; i >= 0; i--)
        {
            sb.Append(str.Substring(i, 1));
        }
        str = sb.ToString();
    }
    return str;
}



Here is another example that accepts a string, splits it, and then reverses the order of words in that string:
private void ReOrderString()
{

string str = "Token A#$%@&Token B#$%@&Token C#$%@&Token D#$%@&Token E"; 
string[] Split = str.Split(new string[] { "#$%@&" }, StringSplitOptions.None);
    StringBuilder sb = new StringBuilder();
    for (int i = Split.Length - 1; i >= 0; i--)
    {
        sb.Append(Split[i]);
        if (i > 0)
            sb.Append("#$%@&");
    }
    lblOriginalString.Text = "Token A#$%@&Token B#$%@&Token C#$%@&Token D#$%@&Token E";
    lblProcessedString.Text = sb.ToString();
}

No comments: