Java StringBuffer codePointCount() 方法



Java 的StringBuffer codePointCount() 方法計算此序列指定文字範圍內的 Unicode 程式碼點的數量。文字範圍從指定的起始索引開始,擴充套件到倒數第二個索引處的字元。因此,文字範圍的長度(以字元為單位)為結束索引 - 開始索引。

如果在給定文字範圍內不存在 Unicode 程式碼點,則該方法不會丟擲任何錯誤,只會列印“0”。

注意 - 未配對的代理程式碼點分別被視為一個單獨的程式碼點。

語法

以下是 Java StringBuffer codePointCount() 方法的語法

public int codePointCount(int beginIndex, int endIndex)

引數

  • beginIndex - 這是文字範圍第一個字元的索引。
  • endIndex - 這是文字範圍最後一個字元之後的索引。

返回值

此方法返回指定文字範圍內的 Unicode 程式碼點的數量。

示例:獲取文字範圍的長度

當我們將輸入文字視為字母時,該方法會返回作為引數給出的文字範圍的長度。

以下示例演示了 Java StringBuffer codePointCount() 方法的使用。

package com.tutorialspoint;

public class StringBufferDemo {

   public static void main(String[] args) {

      StringBuffer buff = new StringBuffer("TUTORIALS");
      System.out.println("buffer = " + buff);

      // returns the codepoint count from index 1 to 5
      int retval = buff.codePointCount(1, 5);
      System.out.println("Count = " + retval);
    
      buff = new StringBuffer("7489042 ");
      System.out.println("buffer = " + buff);
      
      // returns the codepoint count from index 3 to 9
      retval = buff.codePointCount(3, 9);
      System.out.println("Count = " + retval);

      buff = new StringBuffer("@#$%^&");
      System.out.println("buffer = " + buff);
      
      // returns the codepoint count from index 2 to 4
      retval = buff.codePointCount(2, 4);
      System.out.println("Count = " + retval);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

buffer = TUTORIALS
Count = 4
buffer = 7489042
Count = 6
buffer = @#$%^&
Count = 2

示例:獲取沒有有效程式碼點的文字範圍的長度

當我們將輸入文字視為沒有有效程式碼點的字元時,該方法會返回零。

public class StringBufferDemo {

   public static void main(String[] args) {

      StringBuffer buff = new StringBuffer("/u1298139");
      System.out.println("buffer = " + buff);

      // returns the codepoint count
      int retval = buff.codePointCount(0, 0);
      System.out.println("Count = " + retval);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

buffer = /u1298139
Count = 0

示例:在檢查程式碼點數時遇到異常

但是,如果給定的索引引數超過或早於文字範圍,則該方法會丟擲 IndexOutOfBounds 異常。

public class StringBufferDemo {

   public static void main(String[] args) {

      StringBuffer buff = new StringBuffer("djk137");
      System.out.println("buffer = " + buff);
      
      // returns the codepoint count from index 2 to 4
      int retval = buff.codePointCount(-1, 9);
      System.out.println("Count = " + retval);

   }
}

異常

如果我們編譯並執行程式,則會丟擲 IndexOutOfBounds 異常,而不是列印輸出:

buffer = djk137
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.lang.AbstractStringBuilder.codePointCount(AbstractStringBuilder.java:320)
	at java.lang.StringBuffer.codePointCount(StringBuffer.java:227)at StringBufferDemo.main(StringBufferDemo.java:11)
java_lang_stringbuffer.htm
廣告