Knowledge Transfer

Thursday, June 18, 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();
}

Happy coding,
Uday.Adidham
Hyderabad carpool (www.hydcarpool.com)

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();
}

Happy coding,
Uday.Adidham
Hyderabad carpool (www.hydcarpool.com)

Tuesday, June 2, 2009

Fundamental concepts for Javascript

Fundamental concepts for Javascript

Click Here More on Javascript Examples


Regards,
Uday.Adidham
www.hydcarpool.com

Labels: ,