一、length()方法
返回字符串的长度
/*
* @Author:Qiutong
* @Date:2020/7/31
* @Description:实现会员注册
*/
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("***欢迎进入注册系统***");
do {
int flag=0;
System.out.print("请输入用户名:");
String name=input.next();
System.out.print("请输入密码:");
String cipher1=input.next();
System.out.print("请再次输入密码:");
String cipher2=input.next();
if (name.length()<3 || cipher1.length()<6){
System.out.println("用户名长度不能小于3,密码长度不能小于6!");
flag=-1;
}else if(!cipher1.equals(cipher2)){
System.out.println("两次输入密码不相同!");
flag=-2;
}else if(flag==0){
System.out.println("注册成功!请牢记用户名和密码");
break;
}
System.out.println("*****************************");
}while (true);
}
}
二***、equals()方法
字符串的比较方法:
equals()比较两个字符串的内容是否相同, --String类重写过该方法
== 比较两个字符串内存地址是否相等,比较两个字符串是否为同一对象
//字符串创建问题
String s1=“hello”;//字符串池里的
String s2=new String(“hello”);//堆里的
System.out.println(s1.equals(s2));
System.out.println(s1==s2);//此时s1和s2都指向于字符串池中的hello对象 true
String s1=“hello”;//字符串池里的
String s2=new String(“Hello”);//s2指向堆里的"Hello
三、其他方法
trim() 去掉字符串两端的空格
concat()拼接字符串,和+连接两字符串类似
常用的提取和搜索字符串的方法
/*
* @Author:Qiutong
* @Date:2020/7/31
* @Description:输入字符串,查找字符个数
*/
public class StringSite {
//定义一个查找在字符串中的次数方法
public int counter(String str,String find){
int count=0;
String[] chars=new String[str.length()];
for (int i=0;i<chars.length;i++){
chars[i]=str.substring(i,i+1);//字符串拆分开放数组里
if (chars[i].equals(find)){//遍历判断
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("请输入一个字符串:");
String str=input.next();
System.out.print("请输入要查找的字符:");
String find=input.next();
StringSite cha=new StringSite();
int count= cha.counter(str,find);
System.out.println("\""+str+"\""+"中包含了"+count+"个\""+find+"\"");
}
}