Java Character.offsetByCodePoint(CharSequence, int, int)方法

原文:https://www.studytonight.com/java-wrapper-class/java-character-offsetbycodepointscharsequence-seq-int-index-int-codepointoffset-method

Java offsetByCodePoint(CharSequence seq, int index, int codePointOffset)方法是Character类的一部分。该方法返回给定字符序列内的索引,该索引从给定的index偏移codePointOffset码点。在indexcodePointOffset给定的文本范围内,未配对的代理人各算一个码点。

语法:

public static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset)

参数:

传递的参数是:

  • seq -字符序列
  • index -要偏移的索引
  • codePointOffset -代码点的偏移量

返回:

返回字符序列中的索引。

例外情况:

  • NullPointerException -如果seq为空。
  • IndexOutOfBoundsException -如果index为负或大于字符序列的长度。

例 1:

这里返回指定字符序列中的索引。

public class StudyTonight
{  
    public static void main(String[] args)
    {  
        CharSequence cs = "Java is easy"; 

        int index = 0;  
        int codePointOffset = cs.length();  

        int r = Character.offsetByCodePoints(cs,index,codePointOffset);  
        System.out.println("The index within the specified range is : " + r);  
    }
}

规定范围内的指数为:12

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner; 
public class StudyTonight
{  
    public static void main(String[] args)
    {  
        try
        {
            Scanner sc = new Scanner(System.in); 
            System.out.print("Enter the char sequence ");
            CharSequence cs = sc.next();
            System.out.print("Enter index and codePointOffset");

            int index = sc.nextInt();
            int offset = sc.nextInt();

            int r = Character.offsetByCodePoints(cs,index, offset);  
            System.out.println("The index within the specified range is : " + r);
        }
        catch(Exception e)
        {
            System.out.println("Invalid Input!!");
        }
    }
}

今晚进入字符序列学习 输入索引和码点偏移量 2 4 指定范围内的索引为:6

                                                                      • T4】输入字符序列无限 输入索引和码点偏移量 0 9 无效输入!!

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。