Java.lang.String 类

Java 字符串 regionMatches() 方法用于测试两个字符串区域是否相等。该 String 对象的子字符串与参数 other 的子字符串进行比较。如果这些子字符串表示相同的字符序列,则结果为 true。要比较的此 String 对象的子字符串从索引 toffset 开始,长度为 len。要比较的 other 的子字符串从索引 ooffset 开始,长度为 len。

语法

public boolean regionMatches(int toffset,
                             String other,
                             int ooffset,
                             int len) 

参数

toffset 指定该字符串中子区域的起始偏移量。
other指定字符串参数。
ooffset指定字符串参数中子区域的起始偏移量。
len指定要比较的字符数。

返回值

如果该字符串的指定子区域与字符串参数的指定子区域匹配,则返回 true;否则为 false。

异常

无。

示例:

在下面的示例中,regionMatches() 方法用于比较两个字符串区域。

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Hello World!.";
    String str2 = "Hello Java!.";

    //比较两个字符串的前五个字母
    Boolean result = str1.regionMatches(0, str2, 0, 5);

    //打印结果
    System.out.println("Are the String Regions equal?: " + result);
  }
} 

上述代码的输出将是:

Are the String Regions equal?: true