Thursday, 18 October 2012

String Reversal: How to get the reverse string?


String Reversal: How to get the reverse string?

I am discussing a few methods of string Reversal. Please have a look at them.

Method 1:  Using String Concatenation with For Loop:

// string concatenation with for loop
public string ReverseA(string text)
{
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
}

 
Method 2: Using Array.Reverse Method: 

// Array.Reverse function
public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

Method 3: Using Push/Pop Stack:

// push/pop Stack<>
public string ReverseC(string text)
{
    Stack resultStack = new Stack();
    foreach (char c in text)
    {
        resultStack.Push(c);
    }

    StringBuilder sb = new StringBuilder();
    while (resultStack.Count > 0)
    {
        sb.Append(resultStack.Pop());
    }
    return sb.ToString();
}

Method 4: Using Linq

// LINQ
public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}
 

Method 5: Using String Builder

// StringBuilder
public string ReverseE(string text)
{
    char[] cArray = text.ToCharArray();
    StringBuilder reverse = new StringBuilder();
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse.Append(cArray[i]);
    }
    return reverse.ToString();
}


No comments:

Post a comment

Thank You for Your Comments. We will get back to you soon.

back to top