1. Overview
In this
String API
Series, You'll learn
how to get the count of the codepoints in the string for a given text
range.
In the previous article, we have discussed codePointAt() method which is to get the codepoint at the given index.
codePointCount() returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.
Let us jump into codePointCount() method syntax and example programs.
2. codePointCount() Syntax
Syntax:
public int codePointCount(int beginIndex, int endIndex)
This method takes two int arguments for the start index and end index.
beginIndex - the index to the first char of the text range.
endIndex - the index after the last char of the text range.
Exception:
Throws IndexOutOfBoundsException - if the beginIndex is
negative, or endIndex is larger than the length of this String, or
beginIndex is larger than endIndex.
3. Java String codePointCount() Example
package com.javaprogramto.strings;public class StringCodepointCountExample {public static void main(String[] args) {String str = "This is a new method";System.out.println("Input string value : "+str);// Getting count of code points for index 0 to 5int countpointsCount = str.codePointCount(0, 5);System.out.println("Code points count for indexs range (0, 5) :"+countpointsCount);}}
Output:
Input string value: This is a new methodCode points count for indexs range (0, 5) : 5
Example with Broken Heart symbol:
package com.javaprogramto.strings;public class StringCodepointCountExample {public static void main(String[] args) {String heartString = "\uD83D\uDC93\uD83D\uDC93\uD83D\uDC93\uD83D\uDC93";System.out.println("Input string value : "+heartString);// Getting count of code points for index 0 to 4int countpointsCount = heartString.codePointCount(0, heartString.length());System.out.println("Code points count for indexs range (0, 4) : "+countpointsCount);}}
Output:
Input string value : 💓💓💓💓Code points count for indexs range (0, 4) : 4
4. IndexOutOfBoundsException with codePointCount()
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is
larger than the length of this String, or beginIndex is larger than endIndex.
int countpointsCount = heartString.codePointCount(-10, heartString.length());
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsExceptionat java.base/java.lang.String.codePointCount(String.java:788)at com.javaprogramto.strings.StringCodepointCountException.main(StringCodepointCountException.java:12)
5. Conclusion
In this article, you've seen how to use codePointCount() method to get the
count for the given text range.
As usual, All examples shown are over GitHub.
No comments:
Post a Comment
Please do not add any spam links in the comments section.