繁体   English   中英

如何在java中访问字符串数组的每个元素?

[英]How can I access each element of a string array in java?

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

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

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

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

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM