-1

I'm trying to break down a sentence into its words and then output them back in the wrong order.

I can't get to my current error, because the program stops working halfway through the sentence and returns the rest in normal order.

void ReverseString(string input)
{
    string[] subs = input.Split(' ');
    string[] subsc = subs;

    for (int i = 0; i < subs.Length; i++)
    {
        Console.Write(subs[i] + " ");
    }

    for (int i = 0; i < subsc.Length; i++)
    {
        subs[i] = subsc[subsc.Length - 1 - i];
    }

    Console.WriteLine("");

    for (int i = 0; i < subs.Length; i++)
    {
        Console.Write(subs[i] + " ");
    }
}

Usage:

ReverseString("Write a C# program to display the following pattern using the alphabet.");

Results:

Write a C# program to display the following pattern using the alphabet.

alphabet. the using pattern following the display the following pattern using the alphabet.
3
  • string.Join(" ", input.Split(" ").Reverse()) maybe? Commented Aug 29, 2023 at 14:35
  • This is because once you have reached the middle, the lower half now contains the items of the upper half. The upper half items do not exist anymore. Yo must swap the items and do that while i < subs.Length/2. See: C#: Program to swap two numbers. Commented Aug 29, 2023 at 14:36
  • 1
    The line subsc = subs does not create a copy of subs. It makes them both the same array. If you change one, you change the other. So your algorithm doesn't work Commented Aug 29, 2023 at 14:36

2 Answers 2

0

There is no need to create a copy of the array, what, btw., you are not doing. You are only assigning a reference of the same array to another variable.

In a loop swap the first item with the last item, then the second item with the second-last item, and so on...

for (int i = 0, j = subs.Length - 1; i < j; i++, j--)
{
    string temp = subs[i];
    subs[i] = subs[j];
    subs[j] = temp;
}

I assume that you don't know the tuples yet. With them and with the so called deconstruction you could swap the items with:

(subs[i], subs[j]) = (subs[j], subs[i]);

But the first solution with the temp variable totally fine.

Sign up to request clarification or add additional context in comments.

Comments

0

Thx for the help.

            string[] subs = input.Split(' ');
            string[] subsc = input.Split(' ');

I just gave the same input to the second arry so they are now independent from each other.

1 Comment

I think you meant to reply with a comment like this to the other answer to this question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.