Friday, January 15, 2021

Q.4: How to reverse each word in a given string?

 Ans.: The user will input a sentence and we need to reverse each word individually without changing its position in the sentence.

  • input: Welcome to Csharp corner, output: emocleW ot prahsC renroc
internal static void ReverseWords(string str)
{
StringBuilder output = new StringBuilder();
List<char> charlist = new List<char>();
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ' || i == str.Length - 1)
{
if (i == str.Length - 1)
charlist.Add(str[i]);
for (int j = charlist.Count - 1; j >= 0; j--)
output.Append(charlist[j]);
output.Append(' ');
charlist = new List<char>();
}
else
charlist.Add(str[i]);
}
Console.WriteLine(output.ToString());
}

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...