我必须从三个名称字符串(例如ABV PQR SCW)中打印姓氏,以纳入SCW ABV PQR.但是,以下内容并未根据需要

  • 本文关键字:ABV PQR SCW 但是 三个 打印 例如 字符串 java
  • 更新时间 :
  • 英文 :

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 您的字符串

最新更新