2

I want to reverse words in string of java without using split method and StringTokenizer.

For example, How are you must be printed in you are How.

I tried but I failed to do it.

Any help will be appreciated.

Red
  • 26,798
  • 7
  • 36
  • 58
Raaaj
  • 21
  • 1
  • 1
  • 4

3 Answers3

2

Try below code snippet

import java.util.ArrayList;
public class ReverseString
{
    public static void main(String args[])
    {
        String myName = "Here we go";
        ArrayList al = new ArrayList();
        al = recursiveReverseMethod(myName,al);
        al.trimToSize();
        StringBuilder sb = new StringBuilder();
        for(int i = al.size()-1; i>=0;i--)
        {
            sb.append(al.get(i)+" ");

        }
        System.out.println(sb);

    }
    public static ArrayList  recursiveReverseMethod(String myName,ArrayList al)
    {

        int index = myName.indexOf(" ");
        al.add(myName.substring(0, index));
        myName  = myName.substring(index+1);
        if(myName.indexOf(" ")==-1)
        {
            al.add(myName.substring(0));
            return al;
        }
        return recursiveReverseMethod(myName,al);

    }
}
Scientist
  • 1,458
  • 2
  • 15
  • 31
1

Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,

class testers {
    public static void main(String[] args) {
        String testStr="LongString";
        testers u= new testers();
        u.reverseStr(testStr);
    }
    public void reverseStr(String testStr){
        char[] d= testStr.toCharArray();
        int i;
                int length=d.length;
                int last_pos;
                last_pos=d.length-1;
                for (i=0;i<length/2;i++){
                    char tmp=d[i];
                    d[i]=d[last_pos-i];
                    d[last_pos-i]=tmp;

                }
                System.out.println(d);
              }
    }
Community
  • 1
  • 1
sathish_at_madison
  • 823
  • 11
  • 34
1

I would do this:

public static String reverseWordsWithoutSplit(String sentence){
    if (sentence == null || sentence.isEmpty()) return sentence;
    int nextSpaceIndex = 0;
    int wordStartIndex = 0;
    int length = sentence.length();
    StringBuilder reversedSentence = new StringBuilder();
    while (nextSpaceIndex > -1){
        nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
        if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
        else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
        wordStartIndex = nextSpaceIndex + 1;
    }

    return reversedSentence.toString();
}
Prateek
  • 61
  • 6