最近常在面试中遇到这道题,我直接用string的string.split(regex)断成字符串数组然后倒着输出,但这种方法被各种面试官鄙视。刚好今天有时间写一个char级别的反转,,以下是源程序,其实不难,但面试当场不太能写出来。如果可以帮到你,请点个赞。
public class importReverseDisplay {
public static void main(String[] args){
String input;
char stringchar;
int startIndex=0;
int endIndex;
String endString="";
System.out.println("输入");
Scanner scanner=new Scanner(System.in);
input =scanner.nextLine();
char [] charArray=input.toCharArray();
charArray=shuzufanxiang(charArray, 0, charArray.length);
//System.out.println("总体轮转完的结果" +charArray.toString());
/*for (int i = 0; i < charArray.length; i++) {
System.out.println(i+" "+charArray[i]);
}*/
for (int i=0 ; i < charArray.length; i++) {
if (((charArray[i])==' ')||(i==charArray.length-1) ) {
endIndex=i+1;
System.out.print("开始下标"+startIndex+"结束下标"+endIndex+" ");
//System.out.println(i);
char[] a=Arrays.copyOfRange(charArray, startIndex, endIndex);
a=shuzufanxiang(a,0,a.length);
//System.out.print(i+" ");
System.out.println(a);
startIndex=endIndex;
endString=endString+" "+String.valueOf(a);
}
}
System.out.println(endString);
}
public static char[] shuzufanxiang(char[] shuzu,int start,int end){
char stringchar;
for (int i = start; i < end/2; i++) {
stringchar= shuzu[i];
shuzu[i]=shuzu[end-i-1];
shuzu[end-i-1]=stringchar;
//System.out.println(shuzu);
}
System.out.println(shuzu);
return shuzu;
}
}