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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.