String类中的方法

1.lengtn():

获取字符串长度

2.isEmpty():

确认字符串是否为空

3.charAt(int index):

获取Index索引处字符的值

public class StrSource {
    public static void main(String[] args) {
        String str = "hello world";
        System.out.println(str.length());
        System.out.println(str.isEmpty());
        System.out.println(str.charAt(1));
    }
}

输出结果:在这里插入图片描述

4.getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

srcBegin:字符串中要复制的第一个字符的索引
srcEnd:字符串中要复制的最后一个字符之后的索引
dst[]:目标数组
dstBegin:目标数组起始下标

public class StrSource {
    public static void main(String[] args) {
        String str = "hello world";
        char[] arr = new char[12];
        str.getChars(0,8,arr,0);
        System.out.println(Arrays.toString(arr));
    }
}

输出结果:在这里插入图片描述

5.equals()

比较两个字符串的值

public class StrSource {
    public static void main(String[] args) {
        String str = "hello world";
        String str1 = "world hello";
        System.out.println(str.equals(str1));//false
    }
}

6.compareTo()

字符串值的大小比较按照ASCII码的大小比较,大于返回正数,小于返回负数,等于返回0

String str = "abcdef";
String str1 = "abcde";
System.out.println(str.compareTo(str1));//正数1

7.hashCode()

返回对象的哈希码值

String str = "abcde";
String str1 = "Hello world";
System.out.println(str.hashCode());//92599395
System.out.println(str1.hashCode());//-832992604

8.indexOf()

返回字符在字符串中首次出现的位置,没有返回-1;

String str = "Helloworld";
int i = str.indexOf('w',0);
System.out.println(i);//5

9.regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len)

ignoreCase:如果为 true,则比较字符时忽略大小写
toffset:此字符串中子区域的起始位置
other:目标字符串
ooffset:目标字符串中起始位置
len:要比较的长度

String str = "Helloworld";
String str1 = "hello world";
System.out.println(str.regionMatches(true,0,str1,0,5));//true

10.replace()

替换字符串中指定内容

String str = "Hello world";
String str1 = "hello world";
System.out.println(str.replace("Hel","www"));//wwwlo world

11.split(String regex, int limit)

返回由limit分割的字符串数组

String str = "Here is Tulun";
String[] word = str.split(" ");//返回由“ ”分割的字符串
System.out.println(Arrays.toString(word));

12.toLowerCase()

用于把字符串转换为小写

13.toUpperCase()

用于把字符串转换为大写

String str = "Here is Tulun";
System.out.println(str.toLowerCase());//here is tulun
System.out.println(str.toUpperCase());//HERE IS TULUN

14。toCharArray()

将字符串转换成char类型数组存放

String str = "Here is Tulun";
char[] arr = str.toCharArray();
System.out.println(Arrays.toString(arr));
//[H, e, r, e,  , i, s,  , T, u, l, u, n]

15.valueOf()

valueOf() 方法返回 Array 对象的原始值

16.copyValueOf()

拷贝指定范围内的值

char[] array = {'a','b','c','d','e'};
System.out.println(String.valueOf(array));//abcde
System.out.println(String.copyValueOf(array,1,3));//bcd

17.toString()

将任何对象转换成字符串表达形式

char[] array = {'a','b','c','d','e'};
array.toString();
System.out.println(array);//abcde

猜你喜欢

转载自blog.csdn.net/weixin_43289802/article/details/83384727