string input = "Hello World";
input.Reverse().ToArray();
string[] output = input.Split();
string s1 = string.Join(" ", output);
Console.WriteLine(s1.Reverse().ToArray());
It would print ==>"dlroW olleH".
CodePudding user response:
Use Runes to simplify handling any string encoding problems.
public static string ReverseEachWord(this string str)
{
// Open a buffer the same length as the input string
var sb = new StringBuilder(str.Length);
// Open a FILO (First-In, Last-Out) collection to reverse each word
var stack = new Stack<Rune>();
foreach (var rune in str.EnumerateRunes())
{
if (Rune.IsWhiteSpace(rune))
{
// Write the reversed word to the buffer...
while (stack.TryPop(out var stackRune))
{
sb.Append(stackRune);
}
// ... and the space
sb.Append(rune);
}
else
{
// Put on top of the stack
stack.Push(rune);
}
}
// Dump the buffer to a new string
return sb.ToString();
}
CodePudding user response:
Per the comment
var input = "Hello World";
var output = string.Join(
" ",
input.Split().Select(
w => string.Concat(w.Reverse())
)
);
This splits the string to words, reverses each word (resulting in a list of chars that is string.Concat'd back to being a reversed word string) and then re joins them with space separators
Spread out to multiple lines:
var words = input.Split();
var rwords = words.Select(w => string.Concat(w.Reverse()));
var output = string.Join(" ", rwords);