[JAVA]从键盘读入一个英文句子,翻转句子中单词的顺序,String的翻转算法

时间:2023-01-28 20:19:39

同 鹅厂编程题,剑指Offer编程题

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
* Created by 冬瓜 on 2016/9/2.
*/

public class SystemInTest {
public static void main(String[] args) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String str;
try {
str = stdin.readLine();
str = resverStr(str);
String[] strs = str.split(" ");
StringBuffer result = new StringBuffer();
for (String word:strs){
result.append(resverStr(word)+" ");
}
str = result.toString().trim();
System.out.println(str);
String str2 = "abcdefg";
System.out.println(rotateString(str2,2));


} catch (IOException e) {
e.printStackTrace();
}
}

static String resverStr(String str){
if(str == null){
return null ;
}
int length =str.length();
char[] array = str.toCharArray();
char temp ;
for (int i=0;i<(length)/2;i++){
temp = array[i];
array[i]=array[length-1-i];
array[length-1-i]=temp;
}
return String.valueOf(array);
}

static String rotateString(String str,int index){
if(str==null){
return null;
}
StringBuffer sbf = new StringBuffer();
sbf.append(str);
sbf.append(str);//任何字符串的旋转都是 sbf的字串 根据偏移量来subString就能直接拿到结果了
String result = sbf.substring(index,str.length()+index);
return result;
}
}