如何使用 charAt() 函数拆分字符串?

how can i split the string by using charAt() function?

我正在尝试拆分一个包含 3 个不同部分的句子,它们被空格分开。

我已经尝试使用布尔值来计算需要移动到下一部分的位置,但它仍然不起作用并且 return null...

String sentence="name   password   A";
String username;
String password;
char type;

for(int j=0;j<sentence.length();j++){
   SS=sentence.charAt(i)
   String usernamehelper="";
   String passwordhelper="";
   char typehelper=' ';
   boolean usernameend=false;
   boolean passwordend=false;
   boolean typeend=false;

   if(SS!=' ' && usernameend==false){
        usernamehelper += String.valueOf(SS);
   }else if(SS==' ' && usernameend==false){
        usernameend=true;
   }else if(SS!=' ' && usernameend==true && passwordend==false){
        passwordhelper += String.valueOf(SS);
   }else if(SS==' ' && usernameend==true && passwordend==false){
        passwordend=true;
   }else if(SS!=' ' && usernameend==true && passwordend==true){
        typehelper=SS;
        typeend=true;
        username=usernamehelper;
        password=passwordhelper;
        type=typehelper;
        user1=new user(username, password, type);
   }
}

非常感谢!!!

首先,您的代码存在很多问题,例如:变量在 for 循环内初始化,缺少分号...

此外,用多个空格分隔文本是造成问题的原因。

我尝试使用 less if branchs 更正您的代码。请参阅下面的代码

    String sentence="name    password    A";
    String username = "";
    String password ="";
    char SS ;

    //Result : name , password , type
    String[] result = new String[3] ;
    int i= 0 ;

    // To treat multiple spaces 
    boolean previousSpace = false ;

    String textHelper="";

    for(int j=0;j<sentence.length();j++){
        SS=sentence.charAt(j);
        char typehelper=' ';
        boolean typeend=false;

        if(SS!=' '){
            textHelper+=String.valueOf(SS);
            previousSpace = false ;
        }else if(SS==' ' && previousSpace == false ){
            result[i] = textHelper ;    
            textHelper = "" ;
            previousSpace = true ;
            i++ ;
        }

    }

    //Last Text ( type )
    result[i]= textHelper ;

    System.out.println("username " + result[0]);
    System.out.println("password " +result[1]);
    System.out.println("type " + result[2]);

但是,您可以使用 split("\\s+") 方法在两行内完成所有这些操作。

\\s+ :匹配一个或多个空白字符的序列 请参阅下面的代码

    String sentence="name    password    A";
    String[] result =sentence.split("\s+");

    System.out.println("username " + result[0]);
    System.out.println("password " +result[1]);
    System.out.println("type " + result[2]);