Java String: offsetByCodePoint() Method
public int offsetByCodePoints(int index, int codePointOffset)
The offsetByCodePoint() method returns the index within this String that is offset from the given index by codePointOffset code points. Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.
Java Platform: Java SE 8
Syntax:
offsetByCodePoints(int index, int codePointOffset)
Parameter:
Name | Description | Type |
---|---|---|
index | the index to be offset | int |
codePointOffset | the offset in code points | int |
Return Value: the index within this String.
Return Value Type: int
Throws:
IndexOutOfBoundsException - if the index is negative or larger then the length of this String, or if codePointOffset is positive and the substring starting with index has fewer than codePointOffset code points, or if codePointOffset is negative and the substring before index has fewer than the absolute value of codePointOffset code points.
Example: Java String offsetByCodePoints(int index, int codePointOffset) Method
The following example shows the usage of java String() method.
public class StringBufferOffsetByCodePoints {
public static void main(String[] args) {
// initialize the StringBuffer object
StringBuffer strbuff = new StringBuffer("w3resource.com");
System.out.println("\nContents of buffer:" + strbuff);
// get the offsetByCodePoints on index of 3 and an offset of 9
int index = 3;
int codePointOffset = 9;
System.out.println("Result :"
+ strbuff.offsetByCodePoints(index, codePointOffset));
System.out.println();
}
}
Output:
Contents of buffer:w3resource.com Result :12
Example of Throws: string_offsetbycodepoints Method
IndexOutOfBoundsException - if the index is negative or larger then the length of this String, or if codePointOffset is positive and the substring starting with index has fewer than codePointOffset code points, or if codePointOffset is negative and the substring before index has fewer than the absolute value of codePointOffset code points.
Let
int codePointOffset = -9;
In the above example
Output:
Contents of buffer:w3resource.com Exception in thread "main" java.lang.IndexOutOfBoundsEx ception at java.lang.Character.offsetByCodePointsImpl(C haracter.java:5382) at java.lang.AbstractStringBuilder.offsetByCode Points(AbstractStringBuilder.java:321) at java.lang.StringBuffer.offsetByCodePoints(St ringBuffer.java:237) at StringBufferOffsetByCodePoints.main(StringBu fferOffsetByCodePoints.java:15)
Java Code Editor:
Previous:matches Method
Next:regionMatches Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-tutorial/string/string_offsetbycodepoints.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics