String 使用字符数组在java中反转句子的程序

String 使用字符数组在java中反转句子的程序,string,reverse,String,Reverse,我必须颠倒一个句子,但问题是我没有得到准确的输出。 如果输入是今天是星期一,我的输出是y a d n o m s m o d a y 但我得去拿你的东西 请帮帮我 public class reversesentence { public static void main(String[] args) { String sent = "today is monday"; char ch[] = sent.toCharArray(); int

我必须颠倒一个句子,但问题是我没有得到准确的输出。 如果输入是今天是星期一,我的输出是y a d n o m s m o d a y 但我得去拿你的东西 请帮帮我

public class reversesentence {
    public static void main(String[] args) {
        String sent = "today is monday";
        char ch[] = sent.toCharArray();
        int n= ch.length;

//        System.out.println("before reverse:");
//        for(int i=0;i<n;i++){
//            System.out.print(ch[i]+" ");    
//        }

        for(int i=0; i<n; i++){
            //System.out.println("hello");
             ch[i]= ch[n-i-1];

        }

        System.out.println("\nafter reverse:");
        for(int i=0;i<n;i++){
            System.out.print(ch[i]+" ");    
        }
    }

}

如果需要反转字符串,请查看apache commons:

String reversed = org.apache.commons.lang3.StringUtils.reverse(str);

在增加i的同时减少n,不要忘记int n=ch.length-1; 另外,别忘了使用不同的比较-n>=0出现在脑海中

[编辑] 还要注意的是,您不能“就地”执行此操作,您需要一个临时字符串,因为一旦到达中间位置,您就没有字符了:
[/edit]

这听起来像是学校的编程练习

public class reversesentence {
    public static void main(String[] args) {
        String sent = "today is monday";
        char ch[] = sent.toCharArray();
        char tmp;
        int length = ch.length;
        int maxNdx = length - 1;
        int stopAt = maxNdx / 2;

        for (int ndx = 0; ndx < stopAt; ndx++) {
            int ndx2 = maxNdx - ndx;
            tmp = ch[ndx];
            ch[ndx] = ch[ndx2];
            ch[ndx2] = ch[ndx];
        }

        System.out.println();
        System.out.print("After reverse: ");
        for(int i=0;i<n;i++){
            System.out.print(ch[i]+" ");    
        }
    }

}
为了交换内存中的两个项目,您需要第三个位置来临时保存其中一个项目。在这种情况下,tmp是临时位置

要反转数组,将第一个字符替换为最后一个字符,将第二个字符替换为第二个到最后一个字符,等等。因此,只需迭代数组的1/2。该函数使用整数除法将最高数组索引一分为二,这实际上为您提供了数学基础。例如,长度为7的数组的最大索引为6,因此中间的单元格位于索引3处

我一直在打印单个字符,但您可以使用System.out.printlnnew Stringch来代替。

尝试以下方法:


希望这是您想要的。

我会在上面的程序中声明一个小的更正,在该程序中,您已将值存储到一个临时变量中,但忘了进一步使用它

ch[ndx2] = tmp;
ch[ndx2] = tmp;