【问题标题】:how can i split the string by using charAt() function?如何使用 charAt() 函数拆分字符串?
【发布时间】:2023-03-03 05:55:29
【问题描述】:

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

我尝试使用布尔值来计算需要移动到下一部分的位置,但它仍然不起作用并返回 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);
   }
}

非常感谢!!!

【问题讨论】:

  • 您需要使用charAt() 还是对更简单的方法感兴趣?
  • 发布代码时使用适当的缩进。这将使您的代码更易于阅读,并使人们更容易为您提供帮助。
  • 您不仅有格式问题,还有严重的语法错误。缺少分号、未声明的类型等。请重新编辑它并确保它至少可以正确编译。
  • 我不明白你为什么不使用String.split(" ")

标签: java charat


【解决方案1】:

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

另外,有多个空格分隔文本是导致问题的原因。

我尝试使用 less if 分支来更正您的代码。见下面的代码

    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]);

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多