Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the String offsetByCodePoints() method in Java?

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The offsetByCodePoints() method in Java is used to return the index within a string that is the offset from the given index by codePointOffset code points.

Syntax

The offsetByCodePoints() method can be declared as shown in the code below:

public int offsetByCodePoints(int index, int codePointOffset)
  • index: The index that is to be offset.
  • codePointOffset: The offset in code points.

Return value

The offsetByCodePoints() method returns the index within this string that is the offset from the given index by codePointOffset code points.

Note: The offsetByCodePoints() method throws the IndexOutOfBoundsException if it satisfies any of the following conditions:

  • The index is negative.
  • The index is greater than the length of the string.
  • The codePointOffset is positive and the subsequence of the string starting from the index has fewer code points than codePointOffset.
  • The codePointOffset is negative and the subsequence of the string before the index has fewer code points than the absolute value of codePointOffset.

Example

Consider the code below, which demonstrates the use of the offsetByCodePoints() method:

import java.lang.*;
public class Main {
public static void main(String[] args) {
String str = "offsetByCodePoints() example";
System.out.println("str: " + str);
int ind = str.offsetByCodePoints(2, 6);
System.out.println("index = " + ind);
}
}

Explanation

A string str is declared in line 7. The offsetByCodePoints() method is used in line 10 to get the index within str that is the offset from the given index 2 by 6 code points.

RELATED TAGS

java
communitycreator

CONTRIBUTOR

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring