如何在不使用split和stringtokenizer的情况下在java中反转字符串中的单词

时间:2013-11-10 14:38:29

标签: java string reverse

我想在不使用split方法和StringTokenizer的情况下反转java字符串中的单词。 对于前者必须在How are you打印you are How。我试过但是我做不到。 任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

尝试以下代码段

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

    }
}

答案 1 :(得分:1)

这是另一种基于'C'中字符串反转的旧时逻辑的风格,来自此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);
              }
    }

答案 2 :(得分:1)

我会这样做:

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