1. 程式人生 > >String類中的方法

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