java String类

本文详细介绍了Java中String类的各种操作方法,包括字符串的获取、转换、替换等功能,并提供了丰富的示例代码来展示如何使用这些方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String类的获取功能:

int length():获取字符串的长度
char charAt(int index):获取指定索引位置的字符

int indexOf(int ch):返回指定字符在此字符串中第一次出现的索引
为什么这里是int ch而不是char ch呢?
因为我们知道’a’ 和 97都是指的字符 ‘a’,但是定义为int类型的既可以写97也可以写’a’,但是如果定义成char类型的,就只能写’a’,不能写97,因为97是int,int相对于char来说是大的类型,大的类型转换为小的类型需要强转。

int indexOf(String str):返或指定字符串在此字符串中第一次出现的索引
int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现的索引
int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现的索引

String substring(int start):从制定位置开始截取字符串,默认到末尾(包含start)
String substring(int start,int end):从指定位置开始到指定位置结束截取字符串(包含start,不包括end索引)

public class StringDemo {
    public static void main(String[] args) {
        String s = "iloveyoumydear";

        System.out.println(s.length());             //14
        System.out.println(s.charAt(2));            //o

        System.out.println(s.indexOf('y'));         //5
        System.out.println(s.indexOf("you"));       //5
        System.out.println(s.indexOf('c'));         //-1(找不到就返回-1)
        System.out.println(s.indexOf('a'));         //12
        System.out.println(s.indexOf(97));          //12

        System.out.println(s.indexOf('y', 4));      //5
        System.out.println(s.indexOf("you", 3));    //5

        System.out.println(s.substring(8));         //mydear(包含开始的索引)
        System.out.println(s.substring(8, 10));     //my(包含start,不包括end索引)
    }
}

String类的转换功能:

byte[] getBytes():把字符串转换为字节数组
char[] toCharArray():把字符串转换为字符数组
static String valueOf(char[] chs):把字符数组转换为字符串
static String valueOf(int i):把int类型的数据转换为字符串
String类型的valueOf方法可以把任意类型的数据转换为字符串

String toLowerCase():把字符串转换为小写
String toUpperCase():把字符串转换为大写
String concat(String str):

public class StringDemo {
    public static void main(String[] args) {
        String s = "iloveyoumydear";

        //把字符串转换为字节数组(byte类型:-128到127的数字)
        byte[] bys = s.getBytes();
        for(int i = 0;i < bys.length;i++){
            System.out.print(bys[i] + " ");     //105 108 111 118 101 121 111 117 109 121 100 101 97 114 
        }
        System.out.println("");

        //把字符串转换为字节数组
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            System.out.print(chs[i]);           //iloveyoumydear
        }
        System.out.println("");

        //把字符数组转换为字符串
        String ss = String.valueOf(chs);
        System.out.println(ss);                 //iloveyoumydear

        //把int类型的数据转换为字符串
        int i = 100;
        String sss = String.valueOf(i);
        System.out.println(sss);                //100(其实已经是个字符串表示的100)

        //注意:这里吧s转换为大写了是一个新的字符串,但是s本身还是没变的
        System.out.println(s.toUpperCase());    //ILOVEYOUMYDEAR
        System.out.println(s);                  //iloveyoumydear

        //字符串拼接
        String s1 = "hi";
        String s2 = "你好呀";
        String s3 = s1 + s2;
        String s4 = s1.concat(s2);
        System.out.println(s3);                 //hi你好呀
        System.out.println(s4);                 //hi你好呀
    }
}

String类的其他功能:

替换功能:
String replace(char old,char new)
String replace(String old,String new)

去除字符串两端空格
String trim()

按字典顺序比较两个字符串
int compareTo(String str)
int compareToIgnoreCase(String str)

public class StringDemo {
    public static void main(String[] args) {
        //替换功能(都是生成一个新的字符串,原来的字符串是不变的)
        String s = "iloveyoumydear";
        String s1 = s.replace('i', 'I');
        String s2 = s.replace("you", "YOU ");
        System.out.println(s);                  //iloveyoumydear
        System.out.println(s1);                 //Iloveyoumydear
        System.out.println(s2);                 //iloveYOU mydear

        //去除两端空格(都是生成一个新的字符串,原来的字符串是不变的)
        String s3 = " i love you my dear  ";
        System.out.println(s3);                 // i love you my dear  
        System.out.println(s3.trim());          //i love you my dear

        //按字典序比较两个字符
        String s4 = "hello";
        String s5 = "hello";
        String s6 = "you";
        String s7 = "miss";
        System.out.println("h".getBytes()[0]);  //104(h的ASCII值是104)
        System.out.println((int)'y');           //121(y的ASCII值是121)
        System.out.println(s4.compareTo(s5));   //0
        System.out.println(s4.compareTo(s6));   //-17(104 - 121 = -17)
        System.out.println(s4.compareTo(s7));   //-5
    }
}


注意:特殊的情况:

String s8 = "helloyou";
String s9 = "hello";
String s10 = "hel";
System.out.println(s8.compareTo(s9));    //3
System.out.println(s8.compareTo(s10));   //5

我们去看compareTo的源码:

private final char value[];

public String() {
   this.value = "".value;
}

//会把字符串自动转换为一个字符数组
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

public int compareTo(String anotherString) {
    int len1 = value.length;                       //相当于this.value.length,也就是转换为字符数组后字符数组的长度
    int len2 = anotherString.value.length;         //anotherString的长度
    int lim = Math.min(len1, len2);                //取两个字符串的长度小的那个值
    char v1[] = value;                               
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {                              
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {               //取两个字符串中第一个不相等的字符的ASCII的差值
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;               //都相等,就返回字符串长度的差值
}



示例:统计大串中小串出现的次数

//统计大串中小串出现的次数
public class StringDemo {
    public static void main(String[] args) {
        String maxString = "iloveyouiloveyouiloveiloveyouiloveyouyouiloveyou";
        String minString = "iloveyou";

        int count = 0;
        int index; 
        while ((index = maxString.indexOf(minString)) != -1) {  //看大串中是否包含小串,index不等于-1,说明存在,等于-1,就返回count
            count++;
            int startIndex = index + minString.length();       // 开始位置:查找的第一次小串的索引+小串的长度
            maxString = maxString.substring(startIndex);       // 截取从开始位置到结尾的字符串,并赋值给大串
        }
        System.out.println(count); // 5
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值