user2749895
user2749895

Reputation: 27

Swapping each word in a string into a certain order

I am trying to get a string of text from one text box and put it into the next text box inverted but readable like this. "Help please" and in the next box when I click the button it should say "please Help". I have been trying everything that I can think of. Sorry very new to this. Ill attach the code

private void button1_Click(object sender, EventArgs e)
{
    string converttext = txtInputBox.Text;

    StringBuilder sb = new StringBuilder(converttext.Length);
    for (int i = converttext.Length - 1; i >= 0; --i)
    {
        sb.Append(converttext[i]);
    }
    string reversed = sb.ToString();

    txtOutputBox.Text = reversed;
}

Upvotes: 2

Views: 121

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

txtOutputBox.Text = String.Join(" ", txtInputBox.Text.Split().Reverse());

Upvotes: 3

Habib
Habib

Reputation: 223237

You can split the string on space and then reverse the result and pass it to string.Join like:

string str = "Help please";
string newStr = string.Join(" ", str.Split().Reverse());

Upvotes: 4

Related Questions