CodeDev
CodeDev

Reputation: 43

Splitting a string up and joining it back together in reverse order

I want to be able to take a sentence and split it and change the positioning of the words to put the sentence into reverse, there is no set amount of words in the sentence.

Example 1:

Input: "This is a test"
Output: "test a is This"

Example 2:

Input: "Hello World"
Output: "World Hello"

I have been trying for a while now, all I have working is

var stringreversed = stringinput.Split(" ");

But I have no idea where to go from here.

Upvotes: 0

Views: 1773

Answers (2)

MC LinkTimeError
MC LinkTimeError

Reputation: 117

These actions are equal. You can use different function steps or link them all together:

        var s = "This is a string";
        var split = s.Split(' ');
        var reversed = split.Reverse();
        var joined = string.Join(' ', reversed);
        Console.WriteLine(joined); // output: "string a is This"

        var allAtOnce = string.Join(' ', s.Split(' ').Reverse());
        Console.WriteLine(allAtOnce); // output: "string a is This"

Good luck.

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174515

Use String.Split() to split the string, then use Array.Reverse() to reverse the resulting array:

var input = "This is a test";

// Split defaults to splitting on whitespace when you don't supply any arguments
var words = input.Split();

// Reverse the order of the words
Array.Reverse(words);

// Turn back into a string
var reversed = String.Join(" ", words);

Upvotes: 2

Related Questions