Java 字符串類型常用方法


常用方法

獲取字符串長度

public int length()

字符串Unicode操作

這部分用的不多,不是很清楚,先記載在這。

//獲取指定索引處的元素對應的unciode編碼
public int codePointAt(int index)
//獲取指定索引處之前的元素對應的unciode編碼
public int codePointBefore(int index)
//獲取指定的開始索引到結束索引之間元素的unciode編碼的個數
public int codePointCount(int beginIndex, int endIndex)
//獲取指定索引處的元素開始偏移codePointOffset的索引
public int offsetByCodePoints(int index, int codePointOffset)

字符串字符操作

//獲取字符串指定索引處的字符
public char charAt(int index)
//獲取字符串中元素對應的字符數組
void getChars(char dst[], int dstBegin)
//獲取字符串中部分元素對應的字符數組
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
//獲取字符串對應的字符數組
public char[] toCharArray()

字符串字節操作

public byte[] getBytes(String charsetName)
public byte[] getBytes(Charset charset)
public byte[] getBytes()

字符串比較操作

(1)比較是否相等

比較兩個字符串是否相等,anObject 必須為字符串,否則返回 false。

public boolean equals(Object anObject)

比較兩個字符串是否相等,忽略大小寫。

public boolean equalsIgnoreCase(String anotherString)

這兩個方法可用於比較String與StringBuilder,StringBuffer是否相等。

String、StringBuilder、StringBuffer 都實現了 CharSequence 接口,StringBuilder是非線程安全的,而StringBuffer是線程安全的。

public boolean contentEquals(StringBuffer sb)
public boolean contentEquals(CharSequence cs)

(2)比較大小

字符串比較大小。

按字符串中字符的字典順序(也就是字符對應的Unicode值)比較兩個字符串,返回 thisString - anotherString 的差值。

thisString > anotherString,返回值大於0

thisString = anotherString,返回值等於0

thisString > anotherString,返回值小於0

public int compareTo(String anotherString)

字符串比較大小,忽略大小寫。比較方法和上面相同。

public int compareToIgnoreCase(String str)

(3)部分比較是否相等

當某個字符串調用該方法時,表示從當前字符串的 toffset 位置開始,取一個長度為 len 的子串,然后從另一個字符串 other 的 ooffset 位置開始也取一個長度為 len 的子串,然后比較這兩個子串是否相同,如果這兩個子串相同則返回 true,否則返回 false。

public boolean regionMatches(int toffset, String other, int ooffset, int len)

比上面的方法多了一個 boolean 類型的 ignoreCase 參數,用來確定比較時是否忽略大小寫,當 ignoreCase 為 true 表示忽略大小寫。為 false 時和上面方法就相同了。

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

字符串測試操作

(1)開頭測試

字符串的指定索引處是否以指定的一個子字符串開頭。

public boolean startsWith(String prefix, int toffset)

字符串是否以指定的一個子字符串開頭。

public boolean startsWith(String prefix)

(2)結尾測試

字符串是否以指定的一個子字符串結尾

public boolean endsWith(String suffix)

(3)包含測試

字符串是否包含指定的字符序列。

public boolean contains(CharSequence s)

(4)匹配測試

字符串是否能匹配指定的正則表達式

public boolean matches(String regex)

(5)為空測試

該方法其實是判斷字符串的長度是否為0,所以無法判斷含有空格的空串。

public boolean isEmpty()

字符串索引操作

返回在此字符串中第一次出現的指定子串 str 的索引。沒有則返回 -1

從指定的索引 fromIndex 處開始向后搜索(包括該索引),返回在此字符串中第一次出現的指定子字符串 str 的索引。沒有則返回-1。

如果是 int 型參數 ch,則代表的是子串對應的 Unicode 值。

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

返回在此字符串中最后一次出現的指定的子字符串 str 的索引。

從指定的索引 fromIndex 處開始向前搜索(包括該索引),返回在此字符串中最后一次出現的指定子字符串 str 的索引。沒有則返回-1。

如果是 int 型參數 ch,則代表的是子串對應的 Unicode 值。

public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

字符串修改操作

(1)截取

指定開始索引(包含)和結束索引(不包含),截取字符串。

subSequence 和 substring 一樣,源碼里直接調用的 substring。

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
public CharSequence subSequence(int beginIndex, int endIndex)

(2)拼接

會將 str 拼接到源字符串后邊,返回一個新的字符串。

public String concat(String str)

(3)替換

將指定字符 oldChar 或字符序列 target 全部替換為新的字符 newChar 或者新的字符序列 replacement。

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

只會替換第一次出現的匹配正則表達式 regex 的子串。

public String replaceFirst(String regex, String replacement)

會替換所有匹配正則表達式 regex 的子串。

public String replaceAll(String regex, String replacement)

(4)分割

以能匹配正則表達式 regex 的分割符進行分割,分割成指定元素個數 limit 的數組。

public String[] split(String regex, int limit)
public String[] split(String regex)

(5)轉換大小寫

轉換為小寫,可以指定語言環境,一般直接用默認的語言環境,也就是不指定。

public String toLowerCase(Locale locale)
public String toLowerCase()

轉換為大寫

public String toUpperCase(Locale locale)
public String toUpperCase()

(6)去空格

注意:該方法只會去除字符串前后的空格,中間的去不掉。

public String trim()

靜態方法

join拼接新字符串

用指定分隔符 delimiter 分割數組或集合的元素,拼接成新的字符串。

public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

示例:

System.out.println(String.join(":", "aa", "bb", "cc")); // aa:bb:cc
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add("wang");
list.add("bo");
System.out.println(String.join(" ", list)); //hello world wang bo

format格式化字符串

將對象數組按指定格式轉換為字符串。

參考文檔:http://www.cnblogs.com/fsjohnhuang/p/4094777.html

public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)

valueOf轉換字符串

將各種數據類型轉換為字符串

public static String valueOf(Object obj)
public static String valueOf(char data[])
public static String valueOf(char data[], int offset, int count)
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)

copyValueOf拼接字符串

將字符數組中的元素拼接為字符串,可以指定開始索引 offset 和元素總數 count。

public static String copyValueOf(char data[], int offset, int count)
public static String copyValueOf(char data[])

示例:

char[] array = new char[]{'a','b','c','d'};
System.out.println(String.copyValueOf(array));//abcd
System.out.println(String.copyValueOf(array, 2, 1));//c

工具方法

獲取子字符串出現的次數

/**
 * 獲取字符串中子字符串出現的次數
 * @param srcStr
 * @param str
 */
public static void strNum(String srcStr, String str){
    int number = 0;
    for (int i = 0; i < srcStr.length(); i++) {
        if (srcStr.regionMatches(i, str, 0, str.length())) {
            number ++;
        }
    }
    System.out.println("number=" + number);
}

獲取子字符串的所有索引

(1)遞歸實現

/**
 * 獲取字符串中所有子字符串的索引
 * @param srcStr
 * @param str
 * @param i
 */
public static void strIndex(String srcStr, String str, int i){
    int index = srcStr.indexOf(str, i);
    if (index != -1) {
        System.out.println("index=" + index);
        strIndex(srcStr, str, index + str.length());
    }
}

(2)while循環實現

/**
 * 獲取字符串中所有子字符串的索引
 * @param srcStr
 * @param str
 * @param i
 */
public static void strIndex(String srcStr, String str, int i){
    while (true) {
        int index = srcStr.indexOf(str, i);
        if (index == -1) {
            return;
        }
        System.out.println("index=" + index);
        i = index + str.length();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM