操作字符串
String类的常用方法
String类概述
在Java中,字符串被作为String类型的对象来处理。String类位于java.lang包中,默认情况下,该包被自动导入所有的程序。
创建String对象的方法如下
String s=“hello world”;
String s=new String(“hello world”);
String a="abc";
String b="abc";
String c=new String("abc");
String类常用方法
1.求字符串长度length()
字符串.length();
返回字符串的长度。
注册新用户,要求密码不能小于6位
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("******欢迎进入注册系统*********");
boolean flag=false;
do{
System.out.println("请输入用户名") ;
String name=sc.next();
System.out.println("请输入密码");
String pwd=sc.next();
if(name.length()<3||pwd.length()<6){
System.out.println("用户名长度不能小于3,密码长度不能小于6");
continue;
}
System.out.println("请再次输入密码");
String pwd2=sc.next();
if(!pwd.equals(pwd2)){
System.out.println("两次密码不一样,请再输入一次");
continue;
}
System.out.println("注册成功");
flag=true;
}while (!flag);
}
}
2.字符串比较
字符串1.equals(字符串2);
返回值位boolean类型,如果相同,返回真值,否则返回假值。
常用的提取和搜索字符串的方法