Java 中 String 的常用方法(一)

shaopiing發表於2016-05-07

上一篇介紹了 String 中的幾個常用構造方法,由 String 這個核心物件發散出去關於字元的編碼,字元的位元組表達,對 GC 的影響,正規表示式,模式匹配,這可能是 Java 裡內涵最豐富的物件了。今天先講一下 API 中定義的一些常用方法。

1、length 方法

length()
Returns the length of the sequence of characters represented by this object.

返回字串的長度(或者理解為對應字元陣列的長度),如果字串物件的值為 null 則丟擲空指標異常(java.lang.NullPointerException)。

String str = "你好,谷歌!";
String str1 = "Hello, google!";
System.out.println(str.length());
System.out.println(str1.length());

執行結果為:

6
14

2、isEmpty 方法

public boolean isEmpty()
Returns true if length() is 0, otherwise false.

如果字串的長度為 0,則返回 true, 否則返回 false。

如果字串物件的值為 null 則丟擲空指標異常(java.lang.NullPointerException)。

注意:因為在使用過程中,會忘記字串值為 null 的情況,所有判斷字串為空儘量使用 org.apache.commons.lang.StringUtils 中封裝的幾個方法:

  1)isEmpty 方法 

     

     原始碼如下:

public static boolean isEmpty(String str) {
  return str == null || str.length() == 0;
}

  2)isNotEmpty 方法

     

    原始碼如下:

public static boolean isNotEmpty(String str) {
  return !StringUtils.isEmpty(str);
}

  3)isBlank 方法

       

     原始碼如下:

public static boolean isBlank(String str) {
  int strLen;
  if (str == null || (strLen = str.length()) == 0) {
    return true;
  }
  for (int i = 0; i < strLen; i++) {
    if ((Character.isWhitespace(str.charAt(i)) == false)) {
      return false;
    }
  }
  return true;
}

  4)isNotBlank 方法

     

       原始碼如下:

public static boolean isNotBlank(String str) {
  return !StringUtils.isBlank(str);
}

3、charAt 方法

charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

返回索引位置的字元(String 本身就是 char[] 陣列型別)

引數為 int index,範圍為從 0 到 length() -1

如果索引是負數或者大於或等於字串的長度,則會丟擲索引越界異常 IndexOutOfBoundsException。

String str = "hello, google!";
System.out.println(str.charAt(0));
System.out.println(str.charAt(str.length() - 1));

執行結果:

h
!

4、getByte 方法

getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

兩個方法均返回字串對應的(指定編碼方式的)位元組型別陣列。

return new String(str.getBytes("iso-8859-1"), "UTF-8");

5、equals 方法

equals(Object anObject)
Compares this string to the specified object.

比較兩個物件是否內容相等,話不多說,直接上經典的原始碼實現:

通常將常量放在前面,變數放在後邊

String str = "hello, google";
if ("hello, baidu".equals(str)) {
  System.out.println("Are you kidding me?");
} else {
  System.out.println("It's OK!");
}

輸出結果:

It's OK!

6、compareTo 方法

compareTo(String anotherString)
Compares two strings lexicographically.

按照字典順序比較兩個字串,相等返回 0,在 anotherString 前面返回小於 0 的值,否則返回大於 0 的值。

String str = "hello, google";
System.out.println("compare with baidu: " + str.compareTo("hello, baidu"));

輸出結果:

compare with baidu: 5

該方法應用於 Java 中的比較器的實現(內部和外部兩種),有關知識參閱:Java_兩種比較器的實現

PS:外部比較器可以用匿名內部類實現較為簡單,或者用 java8 中的 lambda 表示式更是簡單,相關知識參閱:Java8 初體驗(一)lambda 表示式語法

7、startsWith 方法 和 endsWith 方法

startsWith(String prefix)
Tests if this string starts with the specified prefix.

startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.

endsWith(String suffix)
Tests if this string ends with the specified suffix.

判斷字串是否已給定的字串開頭或者結尾(這裡的引數只能是字串,不支援正規表示式

String str = "hello, google";
System.out.println(str.startsWith("google", 7));

輸出結果:

true

8、hashCode 方法

Returns a hash code for this string.

返回該字串的雜湊值,在初始化物件時,如果該物件可能進行比較,則需要根據要比較的屬性重寫 equals() 和 hashCode() 方法。

9、indexOf 方法 和 lastIndexOf 方法

indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.

lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.

lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

返回的均是索引值(int),還是看圖直觀:

String str = "hello, google";
System.out.println("the second g's index is: " + str.indexOf(103, 8));
System.out.println("google's index is: " + str.indexOf("google"));

輸出結果:

g's index is: 10
google's index is: 7

10、substring 方法

substring(int beginIndex)
Returns a string that is a substring of this string.

substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.

這個方法估計用到的頻率最高了,分隔字串方法,會丟擲索引越界異常。

String str = "hello, google";
System.out.println(str.substring(0, 5));

輸出結果:

hello

記住一點就好:前閉後開 [beginIndex, endIndex)

相關文章