Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to make a new string variable from a reversed string variable?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading