[英]How can I access each element of a string array in java?
I was writing a function to reverse the position of words in a string without reversing the words themselves.我正在编写一个函数来反转字符串中单词的位置,而不反转单词本身。 But I am not able to access the elements of string array.
但我无法访问字符串数组的元素。 I am getting error with the following code.
以下代码出现错误。
public static void reverseWords(String sd[]) {
for(String s : sd){
System.out.println(s);
}
}
To reverse the words in a String array do the following.要反转字符串数组中的单词,请执行以下操作。
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;
}
}
}
Output :输出 :
Michael
Darren
Jeff
Jim
To take in a String as an input try the following.要将字符串作为输入,请尝试以下操作。
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;
}
}
Output :输出 :
store the to went Bob
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.