Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to design a function in which the phrase that a user gives will have a reversal of the words.

For Ex.
User Phrase = "Hello good morning"
will come out to
reverseWordsString = "morning good hello"

NOTE: NOT ALLOWED TO USE ANY STRING OR CHAR METHODS EXCEPT .Length!!
--------------------------------------------------------------------
EDIT NOTE: Must work with the strings alone and any char values you pull out of the strings. You may NOT create or use any arrays or make use of the Array or Char object methods. All standard string methods are all banned

My current solution doesn't work for some reason, except with only two word phrases;

What I have tried:

C#
private static string ReverseWords(string text)
  {
    string reverseWordsString = ""; 
    int secondCounter = text.Length; 
    
    for (int i = text.Length - 1; i >= 0; i--)
    { 
      if(text[i].Equals(' '))
      {
        for(int ii = i + 1; ii < text.Length; ii++)
        {
          reverseWordsString += text[ii];           
        }

        i--; 
        reverseWordsString += " "; 
          } 
    }

    for (int ii = 0; ii < text.Length; ii++)
    {
      if(text[ii].Equals(' '))
      {
        break;
      }
          reverseWordsString += text[ii]; 
    }
        
    return reverseWordsString;
  }
Posted
Updated 5-Jun-22 8:12am
v3
Comments
PIEBALDconsult 4-Jun-22 15:07pm    
"NOT ALLOWED TO USE ANY STRING OR CHAR METHODS"
Do you mean no Methods on the String and Char classes?
Dan L 2022 4-Jun-22 23:27pm    
yes; I can't use the 2 other solutions that was posted as they use .Split methods which I am not allowed to implement (my bad for not specificying), as well as the string builder method.

I will update the note on the question
PIEBALDconsult 4-Jun-22 23:52pm    
Ah, hmm. Is even the concatenation Operator (+) of string forbidden?
Dan L 2022 5-Jun-22 0:09am    
That is allowed (such as I use in the code)

C#
public string ReverseWords(string sentence)
        {
            string result = "";
            string[] words = System.Text.RegularExpressions.Regex.Split(sentence, @"\W");
            System.Array.Reverse(words);
            for(int i = 0; i < words.Length; i++)
            {
                if (i == words.Length - 1)
                    result += words[i];
                else
                    result += words[i] + " ";
            }
            return result;
        }
 
Share this answer
 
v4
Comments
PIEBALDconsult 4-Jun-22 15:03pm    
:cough: StringBuilder :cough:

And not allowed to use String.Split ?
charles henington 4-Jun-22 15:33pm    
updated. Not a fan of StringBuilder but it'll do the job in this case. Strings are immutable therefor are thread safe where StringBuilder is mutable and not thread safe.
PIEBALDconsult 4-Jun-22 15:57pm    
Lack of thread safety is not a reason to avoid StringBuilder.
When thread safety is a concern, it is up to the caller to provide it. Adding thread safety to StringBuilder would make it slow even when thread safety is not a concern.
charles henington 4-Jun-22 16:06pm    
Did I not just say that? Are you blind or did I word it incorrectly? I will never use StringBuilder, that's your choice if you choose to do so!
Tony Hill 4-Jun-22 15:10pm    
The OP stated that they were not allowed to use any string methods except length but your solution uses the string split method.
C#
public static string
ReverseWords
(
  string Value
)
{
  System.Text.StringBuilder result =
    new System.Text.StringBuilder ( Value.Length ) ;

  System.Text.RegularExpressions.MatchCollection mat =
    System.Text.RegularExpressions.Regex.Matches
    ( Value , @"(^|\G)(?'Word'\S+)(?'Sep'\s+)?" ) ;

  for ( int i = mat.Count - 1 ; i >= 0 ; i-- )
  {
    if ( mat [ i ].Groups [ "Sep" ].Success )
    {
      result.Append ( mat [ i ].Groups [ "Sep" ].Value ) ;
    }

    if ( mat [ i ].Groups [ "Word" ].Success )
    {
      result.Append ( mat [ i ].Groups [ "Word" ].Value ) ;
    }
  }

  return ( result.ToString() ) ;
}
 
Share this answer
 
v13
static void Main()
{
    string result = ReverseWords("Hello good morning");
    Debug.Print(result);
}

private static string ReverseWords(string text, int pos = -1, string reverseWordsString = "")
{
    string tempstring = string.Empty;

    if (pos < 0)
    {
        // Start at string end
        pos = text.Length - 1;
    }

    do
    {
        // loop until space
        tempstring = text[pos] + tempstring;
        pos--;
    } while (pos >= 0 && !text[pos].Equals(' '));

    reverseWordsString += " " + tempstring;

    if (pos > 0)
    {
        // Recurse
        reverseWordsString = ReverseWords(text, pos - 1, reverseWordsString);
    }

    return reverseWordsString.Trim();
}
 
Share this answer
 
v3
Comments
Dan L 2022 5-Jun-22 14:59pm    
Hey thanks for your solution, but it doesn't appear to work; if I input Hello World it comes back as " World "
RickZeeland 5-Jun-22 15:21pm    
Thats strange, I get World Hello, are you sure that's a space in between?
Dan L 2022 5-Jun-22 15:53pm    
Ya, I dont know if this makes a difference but I must define the reverseWordsString inside the function itself (inside the Reverse Words function)
RickZeeland 5-Jun-22 15:56pm    
That is problematic I'm afraid ;)
RickZeeland 5-Jun-22 16:01pm    
Ok, updated the solution.
Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C#
private int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!

I'd suggest that you look at what it does wrong first: the symptoms of an error often give you a lot of information about what it is going on that you didn't expect!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900