Free Information Technology Magazines and eBooks

Thursday, May 21, 2009

How to reverse string in C#

On this article, I will show you how to reverse a string in C#. Although this function is not often used in business applications, still you might need it someday. One use of it that I can think of, is including it as part of data encryption process. I'll show you two different functions, first the ReverseWord which will reverse a string by word and the ReverseWordChar that reverse string by each character.



Reverse string by word

public static string ReverseWord(string s)
{
int length = s.Length;
int i = 0;

string[] splittedArray = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (i = splittedArray.Length - 1; i >= 0; i--)
{
if (i != 0)
sb.Append(splittedArray[i] + ' ');
else
sb.Append(splittedArray[i]);

}

return sb.ToString();
}


Reverse string by each character

public static string ReverseWordChar(string s)
{
int length = s.Length;
int i = 0,j=0;
StringBuilder sb= new StringBuilder();
int startPos = length - 1;

for (i = length-1; i >=0;i--)
{
if (s[i] == ' ')
{
for (j = i+1; j <= startPos; j++)
{
sb.Append(s[j]);
}
startPos = i;
sb.Append(' ');
}
}

for (j = 0; j < startPos; j++)
{
sb.Append(s[j]);
}

return sb.ToString();
}

For more C# tips and tricks, subscribe now

1 comments:

Anonymous said...

protected void btnsubmit_Click(object sender, EventArgs e)
{

string str_in = txtinput.Text.Trim();
string output = "";
for (int i = str_in.Length-1; i >= 0; i--)
{
output = output + str_in.Substring(i,1);
}
//txtoutput.Text = output;
char[] cstr = str_in.ToCharArray();
Array.Reverse(cstr);
txtoutput.Text = reversestring(cstr);

}
public string reversestring(char[] newq)
{
return new string(newq);
}