首页 > 解决方案 > 如何在java中访问字符串数组的每个元素?

问题描述

我正在编写一个函数来反转字符串中单词的位置而不反转单词本身。但我无法访问字符串数组的元素。我收到以下代码错误。

 public static void reverseWords(String sd[]) {
   for(String s : sd){
    System.out.println(s);
   }
}

标签: javastring

解决方案


要反转字符串数组中的单词,请执行以下操作。

public class Reverse{
    public static void main(String[] args){

        String[] stringArray = {"Jim", "Jeff", "Darren", "Michael"};

        reverseWords(stringArray);

        for(String strings : stringArray) {
            System.out.println(strings);
        }
    }
    public static void reverseWords(String[] array) {

        for(int i=0; i<array.length/2; i++) {
            String temp = array[array.length-1-i];
            array[array.length-1-i] = array[i];
            array[i] = temp;
        }
    }
}

输出 :

Michael
Darren
Jeff
Jim

要将字符串作为输入,请尝试以下操作。

public class Reverse{
    public static void main(String[] args){

        String sentence = "Bob went to the store";
        String newSentence = reverseWords(sentence);

        System.out.println(newSentence);
    }
    public static String reverseWords(String sentence) {
        //This line splits the String sentence by the delimiter " " or by a space
        String[] array = sentence.split(" ");
        //for loop to reverse the array
        for(int i=0; i<array.length/2; i++) {
            String temp = array[array.length-1-i];
            array[array.length-1-i] = array[i];
            array[i] = temp;
        }

        //These next 4 lines simply take each element in the array
        //and concatenate them all into one String, reversedSentence.
        String reversedSentence = "";
        for(int i=0; i<array.length; i++) {
            //This if statement ensures that no space (" ") is concatenated
            //to the end of the reversedSentence.
            if(i == array.length-1) {
                reversedSentence += array[i];
                continue;
            }
            reversedSentence += array[i] + " ";
        }

        //returning the newly created reversedSentence!
        return reversedSentence;
    }
}

输出 :

store the to went Bob

希望这可以帮助!


推荐阅读