0

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.

2
  • What do you want your new string variable to contain? All of the space-separated words? E.g. if the original is "Foo bar" the final result would be "ooF rab"? Commented Feb 4, 2022 at 0:34
  • No, using your example I would want my final result to be "bar foo" @eric J. Commented Feb 4, 2022 at 0:35

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant , Thanks for your help Eric! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.