Java核心API String类常用方法

String类中的常用方法

String 创建的字符串,调用方法都是在其创建的副本中发生,不会修改字符串本身
StringBuffer可以直接操作字符串本身,直接修改字符串,而不是先创建副本,再对副本进行修改

public class StringDemo01 {
    public static void main(String[] args) {
        //创建String类对象
        String s1 = new String();
        System.out.println("s1:"+s1);
        //通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String
        byte[] bytes = {97,98,99,100,101,102,103};
        String s2 = new String(bytes);
        System.out.println("s2:"+s2);
        //通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String
        String s3 = new String(bytes,0,3);
        System.out.println("s3:"+s3);

        //String(char[] value)
        //          分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
        char [] chars = {'大','湖','名','城'};
        String s4 = new String(chars);
        System.out.println("s4:"+s4);
        //String(char[] value, int offset, int count)
        //          分配一个新的 String,它包含取自字符数组参数一个子数组的字符。
        String s5 = new String(chars,1,2);
        System.out.println("s5:"+s5);
        //String(StringBuilder builder)
        // 分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列
        StringBuilder stringBuilder = new StringBuilder("qwert");
        String s7 = new String(stringBuilder);
        System.out.println("s7:"+s7);

        String s8 = "asdfgjk";
        System.out.println("s8:"+s8);

        //分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列
        StringBuffer stringBuffer = new StringBuffer("1231231");
        String s9 = new String(stringBuffer);
        System.out.println("s9:"+s9);
    }
}

获取字符串长度,length()方法

public class StringDemo02 {
    public static void main(String[] args) {
        String s1 = "qwertyuiopasdfghjklzxcvbnm";
        //获取字符串的长度
        int length = s1.length();
        System.out.println("字符串s1的长度:"+length);
        String s2 = "";
        //获取字符串的长度
        length = s2.length();
        System.out.println("字符串s1的长度:"+length);
        /**
         *
         * 各种元素长度获取方式:
         * 数组长度:数组ming.length
         * 集合长度:集合名.size()
         * 字符串长度:字符串名.length()
         */
    }
}

注册案例+优化:

public class StringDemo03 {
    public static void main(String[] args) {
        //注册用户名密码,要求密码长度不能小于6位
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName = scanner.next();
        System.out.println("请输入密码:");
        String userPasswd = scanner.next();
        //对密码长度进行判断
        /*
        if (userPasswd.length()<6){
            System.out.println("密码长度不能小于六位");
        }
        else {
            System.out.println("注册成功");
        }
*/


        while (userPasswd.length()<6){
            System.out.println("密码长度不能小于六位");
            System.out.println("请重新输入密码");
            userPasswd = scanner.next();
        }
        System.out.println("注册成功");
    }
}

String类中的equals方法

String类中重写了Object类中的equals()方法
String类中的equals()方法比较原理
字符串1:
字符串2:
"=="和String类中的equals方法有什么区别?
equals():检查组成字符串内容的字符是否完全一致
==:判断两个字符串在内存中的地址,判断是否位同一个字符串对象

public class StringDemo04 {
    public static void main(String[] args) {
        String s1 = "qwert";
        String s2 = "qwert";
        String s3 = "asdfg";
        String s4 = "ASDFG";
        //比较两个字符串内容是否相同
        //将字符串转换为字符数组,对每个字符都进行比较,区分字母大小写
        boolean res1 = s1.equals(s2);
        System.out.println(res1);
        boolean res2 = s3.equals(s4);
        System.out.println(res2);
        //不区分大小写进行比较
        boolean res3 = s3.equalsIgnoreCase(s4);
        System.out.println(res3);
    }
}

字符串比较的其他方法,equalsIgnoreCase()方法

public class StringDemo05 {
    public static void main(String[] args) {
        //注册用户名密码,要求密码长度不能小于6位
        Scanner scanner = new Scanner(System.in);
        //登录账号,判断账号密码是否相同,账号不区分大小写,密码区分大小写,密码只能输入三次,三次后不允许再输入
        String userName = "";
        String userPasswd = "";
        int count=0;
        do {
            count++;

            if (count>3){
                System.out.println("密码输入次数已达上限");
                break;
            }
            System.out.println("请输入用户名:");
            userName = scanner.next();
            System.out.println("请输入密码:");
            userPasswd = scanner.next();
        }while (!(userName.equalsIgnoreCase("Tom")&&userPasswd.equals("1234567")));

        if (count<=3){
            System.out.println("登录成功");
        }
    }

}

使用toLowerCase()方法和toUpperCase()方法

public class StringDemo06 {
    public static void main(String[] args) {
        //字符串操作的都是拷贝的内容,字符串本身是没有发生改变
        String s1 = "QqEEQR";
        System.out.println("s1:"+s1);
        //大写转小写
        String lowerCase1 = s1.toLowerCase();
        System.out.println(lowerCase1);
        //小写转大写
        String upperCase1 = lowerCase1.toUpperCase();
        System.out.println(upperCase1);

    }
}

字符串拼接方法

(1) s1+s2
(2) s1.concat(s2)
public class StringDemo07 {
    public static void main(String[] args) {
        String s1 = "eqwer";
        String s2 = "adsfa";
        //字符串拼接方法
        String res = s1+s2;

        System.out.println(res);
        //使用concat()方法拼接
        System.out.println(s1.concat(s2));
        System.out.println(s2.concat(s1));

        System.out.println("=============");

        System.out.println(10+20+"abc");//30abc
        System.out.println(10+"abc"+20);//10abc20
        System.out.println("abc"+10+20);//abc1020
        System.out.println("abc"+(10+20));//abc30

    }
}

字符串常用提取方式

(1) charAt、indexOf和lastIndexOf方法
public class StringDemo08 {
    public static void main(String[] args) {
        //字符串中常用的提取方法
        //
        String s1 = "qwert";
        //字符串的字符索引从0开始
        char ch1 =  s1.charAt(0);
        System.out.println("ch1:"+ch1);
        System.out.println("======================");
        String s2 = "qwertqwertyuiop";

        //int indexOf(int ch)返回指定字符在此字符串中第一次出现处的索引。
        //w的ASCII码值为119
        int index1 = s2.indexOf(119);
        System.out.println("index1:"+index1);
        int index2= s2.indexOf('w');
        System.out.println("index2:"+index2);
        int index3= s2.indexOf('a');
        System.out.println("index3:"+index3);//查找不到返回-1
        // int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
        int index4 = s2.indexOf(119,4);
        System.out.println("从指定位置开始查找w字符,第一次出现的位置是:"+index4);
        int index5 = s2.indexOf('w',4);
        System.out.println("从指定位置开始查找w字符,第一次出现的位置是:"+index5);
        int index6 = s2.indexOf(97,0);
        System.out.println("从指定位置开始查找w字符,第一次出现的位置是:"+index6);

        // int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。
        int index7 = s2.indexOf("we");
        System.out.println("在字符串中查找qwe子字符串,第一次出现的位置是:"+index7);
        int index8 = s2.indexOf("qwe",4);
        System.out.println("从指定位置开始查找qwe字符串,第一次出现的位置是:"+index8);

        // int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

        int index9 = s2.indexOf("tyuiop",3);
        System.out.println("从指定位置开始查找tyuiop字符串"+index9);

        System.out.println("============================");
        String s3 = "qwertabcd";
        //lastIndexOf遍历顺序,至后向前遍历
        // int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。
        int index10 = s3.lastIndexOf('w');
        System.out.println("w在s3中最后一次出现的位置是:"+index10);
        int index11 = s3.lastIndexOf('z');
        System.out.println("z在s3中最后一次出现的位置是:"+index11);//查找不到返回-1

        // int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
        int index12 = s3.lastIndexOf('r',5);
        System.out.println("从字符串中指定位置开始查找r,其最后一次出现的位置是:"+index12);

        // int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
        int index13 = s3.lastIndexOf("abc");
        System.out.println("从字符串中查找abc最后一次出现的位置:"+index13);

        // int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
        int index14 = s3.lastIndexOf("qwert",6);
        System.out.println("从指定位置查找qwert最后一次出现的位置:"+index14);


    }
}
(2) subString()方法和replace()方法
public class StringDemo09 {
    public static void main(String[] args) {

        String s1 = "qwertyuiop";
        System.out.println("s1:"+s1);
        //String substring(int beginIndex) :返回一个新的字符串,它是此字符串的一个子字符串。
        String substring  = s1.substring(1);

        System.out.println("substring:"+substring);

        //replace(char oldChar, char newChar)
        //          返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
        substring.replace('q','w');

        // String substring(int beginIndex, int endIndex) :
        // 返回一个新字符串,它是此字符串的一个子字符串。包含开始索引字符,不包含结束索引字符
        substring  = s1.substring(3,6);
        System.out.println("substring:"+substring);
    }
}

String类中去除字符串首尾空格的方法trim()


public class StringDemo10 {
    public static void main(String[] args) {
        String s1 = "    qwer  rqw  qwer sgd ";
        System.out.println("s1:"+s1);
        /*trim()
        返回字符串的副本,忽略前导空白和尾部空白。*/
        String trimString = s1.trim();
        System.out.println("trimString:"+trimString);
    }
}

String类中的字符串拆分方法,split()方法和getBytes()方法

import java.util.Arrays;

public class StringDemo11 {
    public static void main(String[] args) {
        //字符串拆分
        //        1.split();返回类型是string类型的数组
        //split(String regex)
        //          根据给定正则表达式的匹配拆分此字符串。
        String s1 = "长亭外 古道边 芳草碧连天 晚风拂 柳笛声残 夕阳山外山";
        String[] strings1 = s1.split(" ");
        System.out.println(Arrays.toString(strings1));
        //split(String regex, int limit)
        //根据匹配给定的正则表达式来拆分此字符串。
        String s2 = "长亭外-古道边-芳草碧连天-晚风拂-柳笛声残-夕阳山外山";
        String[] strings2 = s2.split("-");
        System.out.println(Arrays.toString(strings2));

        //getBytes(String charsetName)
        //          使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
        String s3 = "abcdefg";
        byte[] bytes = s3.getBytes();
        System.out.println(Arrays.toString(bytes));
        //遍历数组输出字符串
        for (int i = 0;i < bytes.length;i++){
            //数据类型转换,实现输出字符
            System.out.print((char) bytes[i]);
        }
    }
}

String类中判断字符串开头内容和结尾内容的方法,startWith()和endWith()

public class StringDemo12 {
    public static void main(String[] args) {

        String s1="HelloWorld.java";
        String s2="HelloWorld.class";
        String s3="HelloWordHello.java";
        //endsWith(String value);
        //          测试此字符串是否以指定的后缀结束。
        boolean res1 = s1.endsWith(".java");
        System.out.println(res1);
        //startsWith(String prefix)
        //          测试此字符串是否以指定的前缀开始。
        boolean res2 = s2.startsWith(".java");
        System.out.println(res2);

        boolean res3 = s2.startsWith("Hello");
        System.out.println(res3);
        //startsWith(String prefix, int toffset)
        //          测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
        boolean res4 = s1.startsWith("Hello",1);
        System.out.println(res4);

    }
}

String类练习,查找特定字符出现的次数

package com.bdqn.demo07;

import java.util.Scanner;

public class StringDemo13 {
    String s1 = "";
    String s2 = "";

    public static void main(String[] args) {
        //查找一个特定字符出现的次数
        //1.将字符串转换为byte数组,遍历数组进行比对
        Scanner scanner = new Scanner(System.in);

        String s1 = "";
        String s2 = "";
        s1 = scanner.next();
        s2 = scanner.next();
        int count = 0;
        byte[] bytes = s1.getBytes();
        byte[] bytes1 = s2.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            Character char1 = (char) bytes[i];
            Character char2 = (char) bytes1[0];
            if (char1.equals(char2)){
                count++;
            }

        }
        System.out.println("s2在s1中出现的次数为:"+count);

        //2.使用索引判断,每次查找字符串中第一次出现的s2,再对字符串进行截取,保证每次查找到的s2不是同一个,直到查找不到s2
        count = 0;
        while (true){
            int index = s1.indexOf(s2);
            if (index!=-1){
                count++;
                s1 = s1.substring(index+1);

            }else {
                break;
            }
        }
        System.out.println("s2在s1中出现的次数为:"+count);

    }
}

String类中的其他常用方法

public class StringDemo14 {
    public static void main(String[] args) {

        char[] chars = {'大','湖','名','城',',','创','新','高','地','!'};
        //static String valueOf(char[] data) 返回 char 数组参数的字符串表示形式。
        //static String valueOf(char[] data, int offset, int count) 返回 char 数组参数的特定子数组的字符串表示形式。
        String s1 = String.copyValueOf(chars);
        System.out.println(s1);

        String s2 = String.copyValueOf(chars,2,6);
        System.out.println(s2);

//        isEmpty()方法判断是否为空
        Boolean ret = s2.isEmpty();
        System.out.println(ret);
    }
}

StringBuffer类及其常用方法

对字符串频繁修改如字符串连接时,使用StringBuffer类可以大大提高程序执行效率

public class StringBufferDemo01 {

    public static void main(String[] args) {
        //创建StringBuffer类对象
        StringBuffer stringBuffer1 = new StringBuffer("qweqwert");
        System.out.println("stringBuffer1:"+ stringBuffer1);
        //append最加操作
        StringBuffer stringBuffer2 = stringBuffer1.append(true);
        System.out.println("stringBuffer2:"+stringBuffer2);//qweqwerttrue

        System.out.println("stringBuffer1:"+ stringBuffer1);//qweqwerttrue

        System.out.println("=====================================");

        char[] chars = {'a','b','c','d','e'};
        System.out.println(stringBuffer1.append(chars));//qweqwerttrueabcde
        System.out.println(stringBuffer1.append(chars,1,3));
        System.out.println("======================================");//qweqwerttrueabcdebcd

        StringBuffer stringBuffer3 = new StringBuffer("asdfgjkl");//asdfgjkl
        System.out.println("stringBuffer3:"+stringBuffer3);

        //insert()方法
        //向stringBuffer3内指定位置插入数据

        StringBuffer stringBuffer4 = stringBuffer3.insert(2,false);//asfalsedfgjkl
        System.out.println("stringBuffer4:"+stringBuffer4);
        System.out.println("stringBuffer3:"+stringBuffer3);


        System.out.println(stringBuffer3.insert(7,chars));//asfalseabcdedfgjkl
        System.out.println(stringBuffer3.insert(17,chars,2,2));//asfalseabcdedfgjkcdl
        
    }
}

StringBuilder类


public final class StringBuilder
extends Object
implements Serializable, CharSequence

一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer 要快。

小结

String类 StringBuffer类 StringBuilder类比较
StringBuilder类效率>StringBuffer类>String类
String 创建的字符串不能修改(调用方法都是对其副本进行操作,字符串本身不发生改变)
StringBuffer和StringBuillder创建的字符串可以修改(调用方法,直接操作字符串本身)

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值