java 15.String

String

java.lang.String

String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类的实例。

  1. 字符串的内容永不变; 它们的值在创建后不能被更改。

  2. 因为String对象是不可变的,所以它们可以被共享。

  3. 字符串效果上相当于是char[]字符数组,但是底层原理是byte[]字节数组。

创建字符串常见的3+1种方式

创建一个空白字符串,不含任何内容

public String()

根据字符数组的内容,创建对应的字符串

public String(char[] array)

根据字节数组的内容,创建对应的字符串

public String(byte[] array)

一种直接创建

String s = "Hello";

示例代码

    public static void main(String[] args) {
        String s1 = new String();
        System.out.println("第一个字符串:"+s1);

        char[] charArray = {'A','B','C'};
        String s2 = new String(charArray);
        System.out.println("第二个字符串:"+s2);

        byte[] byteArray = {97,98,99};
        String s3 = new String(byteArray);
        System.out.println("第三个字符串:"+s3);

        String s4 = "hello";
        System.out.println("第四个字符串:"+s4);
    }

字符串的常量池

public class demo001 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";

        char[] charArray = {'a','b','c'};
        String s3 = new String(charArray);

        System.out.println(s1 == s2);  //true
        System.out.println(s1 == s3);  //false
        System.out.println(s2 == s3);  //false
    }

}

原理

  • 对于引用类型,==进行的是地址值的比较
  • 双引号直接写的字符串在常量池当中,new的不在常量池中
    在这里插入图片描述

字符串内容的比较方法

==是进行对象的地址值比较,如果确实需要字符串的内容比较,可以使用两个方法:

第一个

//参数可以是任何对象,只有参数是一个字符串并且内容相同的才会给true,否则返回false
public boolean equals(Object obj);

备注

  1. 任何对象都能用object进行接收。

  2. equals方法据有对称性,也就是a.equals(b)和b.equals(a)效果一样

  3. 如果比较双方一个常量一个变量,推荐把常量字符串写在前面,比如:“abc”.equals(s3)

public class demo001 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";

        char[] charArray = {'a','b','c'};
        String s3 = new String(charArray);

        System.out.println(s1.equals(s2));  //true
        System.out.println(s2.equals(s3));  //true
        System.out.println(s3.equals("abc"));  //true
        System.out.println("abc".equals(s3));  //true
    }

}

第二个

//忽略大小写,进行内容比较
public boolean equalsIgnoreCase(String str)
public class demo001 {
    public static void main(String[] args) {
        String s1 = "abc123C d";
        String s2 = "ABC123c D";

        System.out.println(s1.equalsIgnoreCase(s2));  //true
        System.out.println("ABC123c D".equalsIgnoreCase(s1));  //true
    }
}

字符串的获取方法相关

public int length();  //获取字符串长度
public String concat(String str);  //将当前字符串和参数字符串拼接成为返回值的新字符串
public char charAt(int index);  //获取索引位置的单个字符,索引从0开始
public int indexOf(String str);  //查找参数字符串在本字符串中首次出现的索引位置,如果没有返回-1值
public class demo001 {
    public static void main(String[] args) {
        String s1 = "hello hello hello ";
        String s2 = "world";

        System.out.println(s1.length());
        System.out.println(s1.concat(s2));
        System.out.println(s1.charAt(2));
        System.out.println(s1.indexOf("llo"));
        System.out.println(s1.indexOf("wor"));
    }
}

字符串截取

//截取从参数位置一直到字符串末尾,返回新字符串
public String substring(int index);  
//截取从begin开始,一直到end结束,中间的字符串,不包含begin和end
public String substring(int begin, int end)
public class demo001 {
    public static void main(String[] args) {
        String s1 = "hello world";
        System.out.println(s1);  //hello world
        String s2 = s1.substring(5);
        System.out.println(s2);  //world
        String s3 = s1.substring(5,8);
        System.out.println(s3);  //wo
    }
}

字符串转换相关常用方法

//将当前字符串拆分成为字符数组作为返回值
public char[] toCharArray()
//获得当前字符串底层的字节数组
public byte[] getBytes()
//将所有出现的老字符串替换成为新的字符串,返回替换后的结果新字符串
//CharSequence意思就是说可以接收字符串类型
public String replace(CharSequence oldString, CharSequence newString)    
public class demo001 {
    public static void main(String[] args) {
        char[] chars = "Hello".toCharArray();
        System.out.println(chars[0]);  //chars可以作为数组来使用,否则String无法这样用

        byte[] bytes = "abc".getBytes();  //转换成字节数组来使用
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);  //97 98 99
        }

        String s1 = "How do you do?";
        String s2 = s1.replace("o","*");
        System.out.println(s2);  //H*w d* y*u d*?
    }
}

字符串分割

//按照参数规则,将字符串切分为若干部分
public String[] split(String regex)

注意

参数regex是正则表达式,所以如果按照点号.切割,必须转译,比如这样"\\."

public class demo001 {
    public static void main(String[] args) {
        String ip = "192.168.172.55";
        String[] ips = ip.split("\\.");
        for(String i: ips){
            System.out.println(i);
        }
    }
}

练习题

题目1

定义一个方法,把数组{1,2,3}按照指定格式拼接成一个字符串,格式如下:[word1#word2#word3]

public class demo001 {
    public static void main(String[] args) {
        String[] arr1 = {"user","password","token"};
        int[] arr2 = {192,168,1,10};
        String r1 = fromArrayToString(arr1);
        String r2 = fromArrayToString(arr2);
        System.out.println(r1);
        System.out.println(r2);
    }

    public static String fromArrayToString(String[] arr) {
        String result = "[";
        for (int i = 0; i < arr.length; i++) {
            if (i==arr.length-1){
                result += arr[i] + "]";
            }else {
                result += arr[i] + "#";
            }
        }
        return result;
    }
    //重载方法,支持int型数组入参
    public static String fromArrayToString(int[] arr) {
        String result = "[";
        for (int i = 0; i < arr.length; i++) {
            if (i==arr.length-1){
                result += arr[i] + "]";
            }else {
                result += arr[i] + "#";
            }
        }
        return result;
    }
}
题目2

键盘输入一个字符串,并且统计其中各种字符出现的次数。

种类有:大写字母、小写字母、数字、其他

import java.util.Scanner;

public class demo001 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        int counterUpper = 0; //大写字母
        int counterLower = 0; //小写字母
        int counterNumber = 0; //数字
        int counterOther = 0; //其他
        if(sc.hasNextLine()){
            String input = sc.nextLine();
            char[] chars = input.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char ch = chars[i];
                if ('A' <= ch && ch <= 'Z'){
                    counterUpper++;
                }else if('a' <= ch && ch <= 'z'){
                    counterLower++;
                }else if('0' <= ch && ch <= '9'){
                    counterNumber++;
                }else {
                    counterOther++;
                }
            }
        }
        sc.close();
        System.out.println("大写字母出现次数统计结果:" + counterUpper);
        System.out.println("小写字母出现次数统计结果:" + counterLower);
        System.out.println("数字出现次数统计结果:" + counterNumber);
        System.out.println("其他字符出现次数统计结果:" + counterOther);
    }
}

next() 与 nextLine() 区别

next():

  • 1、一定要读取到有效字符后才可以结束输入。
  • 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  • 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine():

  • 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 2、可以获得空白。

注意:在读取前我们一般需要 使用 hasNext 与 hasNextLine 判断是否还有输入的数据

import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            //String str2 = scan.next();
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
        scan.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我是一言

让我看看你的头像

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

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

打赏作者

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

抵扣说明:

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

余额充值