Java codePointBefore 方法

Java codePointBefore 方法是 String 方法之一,用于返回指定索引位置之前字符的 Unicode。在本文中,我们将通过一个示例展示如何在该编程语言中使用 codePointBefore 方法。索引位置从 0 开始,而不是 1。

Java 编程语言中 codePointBefore 的基本语法如下所示。

public int codePointBefore(int Index_Position) 

//In order to use in program
String_Object.codePointBefore(int Index_Position)
  • String_Object:请指定有效的 String 对象。
  • Index_Position:请指定所需字符的索引位置。

此 codePointBefore 函数将返回 String_Object 中指定 Index_Position 减 1 的字符的 Unicode 值。例如,如果我们指定 codePointBefore(5),它将返回索引位置 4 处字符的 Unicode 值。如果我们指定超出范围的索引位置或负值,则函数将抛出错误。

Java codePointBefore 示例

在此程序中,我们将使用字符串 codePointBefore 方法返回指定索引位置减 1 处的字符的 Unicode 值。

package StringFunctions;

public class CodePointBefore {
	public static void main(String[] args) {
		String str = "Learn Free Java Tutorial";
		
		int a = str.codePointBefore(1);
		int b = str.codePointBefore(11);
		int c = str.codePointBefore(22);
		int d = str.codePointBefore(str.length()- 1);
		
		System.out.println( "Unicode Vlaue of Character at Index position 0 = " + a);
		System.out.println( "Unicode Vlaue of Character at Index position 10 = " + b);
		System.out.println( "Unicode Vlaue of Character at Index position 21 = " + c);
		System.out.println( "Unicode Vlaue of Character at Last Index position - 1 = " + d);
	}
}
codePointBefore Method

在此 Java codePointBefore 方法示例中,我们声明了 String 变量并为其赋值。

以下 codePointBefore String 方法语句将查找索引位置 0、10、21 处的字符。然后将这些字符的 Unicode 值赋给整数变量 a、b 和 c。

int a = str.codePointBefore(1);
int b = str.codePointBefore(11);
int c = str.codePointBefore(22);

如果您观察上面的屏幕截图,str.codePointAt(11) 返回 32。这是因为我们都知道索引位置 10 处的字符是空格,根据 ASCII 表,空格的 Unicode 值是 32。您应该将空格计为一个字符。请参考 ASCII 表 来查看每个字符的代码。

在下一行,我们将使用 length 函数 和 codePointBefore 来计算字符串长度。

int d = str.codePointBefore(str.length()- 1);

从上面的代码片段中,我们从字符串长度中减去一。因为字符串的长度是从 1 到 n 计算的,而索引位置是从 0 开始到 n-1 结束。以下四个 Java System.out.println 语句将打印输出。