如何反转字符串

时间:2015-11-26 17:45:22

标签: java arrays

我有来自学校的这个作业,但我不确定我做错了第二个阵列没有采取第一个的价值,你能帮我吗?

public static void main(String[] rpp) {

        String[] word = new String[7];        
        word[0] = "D";
        word[1] = "E";
        word[2] = "N";
        word[3] = "T";
        word[4] = "I";
        word[5] = "S";
        word[6] = "T";        

        String[] inverseWord = new String[7];
        inverseWord[0] = "";
        inverseWord[1] = "";
        inverseWord[2] = "";
        inverseWord[3] = "";
        inverseWord[4] = "";
        inverseWord[5] = "";       


        for(int x = word.length;x <= 0;x--){
            for(int y = 0;y <= word.length;y++){
                inverseWord[y] = word[x];                
            }            
        }        
        System.out.print(Arrays.toString(inverseWord) + "\n");
    }

5 个答案:

答案 0 :(得分:2)

数组索引从0开始。这意味着如果长度为L,则数组中的最后一个索引将为(L-1)。

这意味着您需要撰写int x = word.lengthint x = word.length - 1而不是y <= word.length而不是y < word.length

此外,外部循环中的条件应为y <= word.length - 1,而不是x >= 0

答案 1 :(得分:1)

  1. 您不需要两个for循环
  2. x应大于等于0且不小于
  3. public static void main(String[] rpp) {
        String[] word = new String[7];
        word[0] = "D";
        word[1] = "E";
        word[2] = "N";
        word[3] = "T";
        word[4] = "I";
        word[5] = "S";
        word[6] = "T";
    
        String[] inverseWord = new String[7];
        inverseWord[0] = "";
        inverseWord[1] = "";
        inverseWord[2] = "";
        inverseWord[3] = "";
        inverseWord[4] = "";
        inverseWord[5] = "";
    
        for (int x = word.length - 1; x >= 0; x--) {
            inverseWord[(word.length-1) - x] = word[x];
        }
        System.out.print(Arrays.toString(inverseWord) + "\n");
    }
    

答案 2 :(得分:0)

外部for循环的条件应为

x&gt; = 0

答案 3 :(得分:0)

使用2个变量重写用于反转的for循环。这是最简单和最基本的方法。

 for(int i=word.length-1,int j=0;i>=0,j>=0;i--,j++) //loop for reversing
            {
                inverseWord[j] = word[i];
            }

    for(int i=0;i>=0;i++) // for displaying the inverseword array
    {
    System.out.print(inverseWord[j];
    }

答案 4 :(得分:0)

您可以使用StringBuilder将单个字符附加到String中。字符串“DENTIST”可以使用String类中的charAt方法和for循环分解为相反顺序的字符。

public class MainClass {

    public static void main(String[] args) {
        String word = "DENTIST";
        StringBuilder inverseWord = new StringBuilder();

        for (int i = word.length()-1; i >= 0; i--) {
            inverseWord.append(word.charAt(i));
        }
        System.out.println(inverseWord);

    }

}