import java.util.Scanner;
class Chan{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int a,i;
char c;
String st="";
int d=0;
String s1="";
String s2="";
a=s.length();
for(i=0;i<a;i++){
c=s.charAt(i);
if(c==' '){
d=d+1;
}
if(d==2){/d is 2 at the space at third name
s1=s.substring(i,a);
st=s.substring(0,i);
}
}
s2=s1+" "+st;
System.out.println(s2);
}
}
此代码仅通过在整个名称之前添加姓氏的最后一个字符来执行。代码中有什么错误?
尝试在空间上拆分
String input = "ABC DEF GHI";
String arr [] = input.split (" ");
System.out.println (arr[2] + " " + arr[0] + " " + arr[1]);
NOTE 最好将StringBuilder用于 recuild 您的字符串