Java StringBuilder.offsetByCodePoints() – Examples
In this tutorial, we will learn about the Java StringBuilder.offsetByCodePoints() function, and learn how to use this function with the help of examples.
offsetByCodePoints(int index, int codePointOffset)
StringBuilder.offsetByCodePoints() returns the index within this sequence that is offset from the given index by codePointOffset code points.
Syntax
The syntax of offsetByCodePoints() function is
offsetByCodePoints(int index, int codePointOffset)
where
Parameter | Description |
---|---|
index | The index in the sequence from which we have to travel the offset. |
codePointOffset | The offset from index in code points. |
Returns
The function returns an integer.
Example 1 – offsetByCodePoints(index, codePointOffset)
In this example, we will take an empty StringBuilder, and append some code points to it. Now we shall find the index in this sequence, that is offset from the given index
by codePointOffset
code points. We shall take index as 1 and codePointOffset as 4 for this example.
Java Program
public class Example {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.appendCodePoint(658550);
stringBuilder.appendCodePoint(658550);
stringBuilder.appendCodePoint(658550);
stringBuilder.appendCodePoint(55523);
stringBuilder.appendCodePoint(55452);
stringBuilder.appendCodePoint(555);
stringBuilder.appendCodePoint(55856);
stringBuilder.appendCodePoint(557);
int offset = stringBuilder.offsetByCodePoints(1, 4);
System.out.println("Sequence is : " + stringBuilder.toString());
System.out.println("Offset is : " + offset);
}
}
Output
Sequence is : ??ȫ?ȭ
Offset is : 7
Example 2 – offsetByCodePoints(index, codePointOffset)
In this example, we will take an empty StringBuilder, and append some code points to it. These code points translate to single character. Meaning, when we call offsetByCodePoints(), it would return index + codePointOffset;
Java Program
public class Example {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.appendCodePoint(97);
stringBuilder.appendCodePoint(98);
stringBuilder.appendCodePoint(99);
stringBuilder.appendCodePoint(100);
stringBuilder.appendCodePoint(101);
stringBuilder.appendCodePoint(102);
stringBuilder.appendCodePoint(103);
stringBuilder.appendCodePoint(104);
int offset = stringBuilder.offsetByCodePoints(1, 4);
System.out.println("Sequence is : " + stringBuilder.toString());
System.out.println("Offset is : " + offset);
}
}
Output
Sequence is : abcdefgh
Offset is : 5
Conclusion
In this Java Tutorial, we have learnt the syntax of Java StringBuilder.offsetByCodePoints() function, and also learnt how to use this function with the help of examples.