Thursday, 19 June 2014

offsetByCodePoints (int index, int codePointOffset)

public int offsetByCodePoints(int index, int codePointOffset)
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.

class StringOffsetByCodePoints{
 public static void main(String args[]){
  char arr1[] = {'d', 'e', 'f', 'g', 'h', 'i'};
  int arr2[] = {65536, 65537, 65538, 65539, 65540, 65541};
  
  String s1 = new String(arr1);
  String s2 = new String(arr2, 0 , arr2.length);
  
  System.out.println(s1.offsetByCodePoints(1, 3));
  System.out.println(s2.offsetByCodePoints(1, 3));
 }
}

Output
4
6

1. Throws IndexOutOfBoundsException if index is negative or larger than 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.
class StringOffsetByCodePointsIndexOut{
 public static void main(String args[]){
  char arr1[] = {'d', 'e', 'f', 'g', 'h', 'i'};
  
  String s1 = new String(arr1);
  
  System.out.println(s1.offsetByCodePoints(1, 7));
 }
}

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException
        at java.lang.Character.offsetByCodePointsImpl(Character.java:5371)
        at java.lang.String.offsetByCodePoints(String.java:762)
        at StringOffsetByCodePointsIndexOut.main(StringOffsetByCodePointsIndexOut.java:7)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment