Home > Software engineering >  Splitting a string up and joining it back together in reverse order
Splitting a string up and joining it back together in reverse order

Time:10-27

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.

CodePudding user response:

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);

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related