Home > Software design >  Is there a way to make a new string variable from a reversed string variable?
Is there a way to make a new string variable from a reversed string variable?

Time:02-04

The code I have used to reverse the original string is...

foreach (var revString in strExample.Split(' ').Reverse()) Console.WriteLine(revString);

However I am struggling to create a new string variable following this method. Can anyone help me out. I am new to coding and don't fully understand everything yet.

CodePudding user response:

String.Join() does the reverse of String.Split(), so you can do this:

var strExample = "Foo bar";
var reversed = string.Join(' ', strExample.Split(' ').Reverse());

bar Foo

If you also wanted to reverse the letters within each word (original comment before edited):

var fullyReversed = 
    string.Join(' ', strExample.Split(' ')
    .Select(word => new string(word.Reverse().ToArray())));

ooF rab

or more simply:

new string(strExample.Reverse().ToArray());
  •  Tags:  
  • Related