【7.31笔记】String类的常用方法

一、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+"\"");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

youzi-qiu7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值