需求:
反转字符串中单词的位置
例如: i love testing
反转位置后:testing love i
思路:
有很多解决思路,字符串转换成数组,再反向输出数组元素。这里我们介绍类似《Java Coding 12 - 反转字符串中的每个单词》反向遍历字符串,找到空格,空格后字符就是第一个单词的起始位置,结束位置是字符串结束位置。第二个单词起始位置是第二个空格后字符的位置,结束位置是第一个空格前的字符位置,依次类推。。。。最后一个单词的起始位置是0.
实现:
public static String reversePositionOfWordsInString(String str){
int len = str.length();
String revertedStr = "";
int wordEndIndex = len - 1;
int wordStartIndex;
for(int i = len -1; i >= 0; i--){
if(str.charAt(i) == ' ' || i == 0){
if(i == 0){
wordStartIndex = i;
}else{
wordStartIndex = i + 1;
}
for(int j = wordStartIndex; j<= wordEndIndex; j++){
revertedStr = revertedStr + str.charAt(j);
}
revertedStr = revertedStr + " ";
wordEndIndex = i - 1;
}
}
return revertedStr;
}
完整代码:
import java.util.*;
public class Test {
public static void main(String[] args) {
testReversePositionOfWordsInString();
}
public static void testReversePositionOfWordsInString(){
System.out.println("please enter a string, input quit means to exit");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
while(!str.equals("quit")){
System.out.println("after reverse the position of words in the string " + str);
System.out.println(reversePositionOfWordsInString(str));
System.out.println("please enter a string again, input quit means to exit");
str = in.nextLine();
}
}
public static String reversePositionOfWordsInString(String str){
int len = str.length();
String revertedStr = "";
int wordEndIndex = len - 1;
int wordStartIndex;
for(int i = len -1; i >= 0; i--){
if(str.charAt(i) == ' ' || i == 0){
if(i == 0){
wordStartIndex = i;
}else{
wordStartIndex = i + 1;
}
for(int j = wordStartIndex; j<= wordEndIndex; j++){
revertedStr = revertedStr + str.charAt(j);
}
revertedStr = revertedStr + " ";
wordEndIndex = i - 1;
}
}
return revertedStr;
}
}