写一个翻转函数,使字符串倒叙
?
?
先把整个句子翻转
?
?
然后以空格为split,分割字符串
?
?
对单个字符再进行翻转,然后重新组合
?
?
package reverseSentence42;
?
?
public class ReverseSentence42 {
static String reverse(String string) {
char[] array = string.toCharArray();
int i = 0, j = array.length - 1;
while (i < j) {
char tem = array[i];
array[i] = array[j];
array[j] = tem;
i++;
j--;
}
return String.valueOf(array);
}
static String reverseSentence(String string){
String reversedString=reverse(string);
String[] splitStrings=reversedString.split(" ");
String resultString="";
for(String str:splitStrings){
resultString=resultString+reverse(str)+" ";
}
return resultString;
?
?
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String string="abcd edfs";
System.out.println(reverseSentence(string));
}
?
?
}
时间: 2024-10-25 02:25:57