介绍
在 Java 中,String 类的 regionMatches() 方法用于比较两个字符串中指定区域的字符是否相等。它可以灵活地指定比较的起始位置和长度,并且支持忽略大小写的比较。
方法定义
regionMatches() 有两个重载版本:
区分大小写
public boolean regionMatches(int toffset, String other, int ooffset, int len)
可指定是否忽略大小写
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
参数说明
ignoreCase:若为true,则忽略大小写比较;false则区分大小写(仅第二个版本有此参数)。toffset:当前字符串中开始比较的起始索引。other:要比较的另一个字符串。ooffset:另一个字符串中开始比较的起始索引。len:要比较的字符数量。
返回值
- 若两个指定区域的字符序列相等(考虑大小写或忽略大小写),返回
true;否则返回false。
注意事项
- 若参数
len为0,则始终返回true(空区域默认相等)。 - 若指定的区域超出任一字符串的边界(如起始索引 + 长度超过字符串长度),则返回
false。 - 忽略大小写比较时,会将字符转换为大写(或小写)后再比较(如
'A'和'a'视为相等)。
例子
public class RegionMatchesExample {
public static void main(String[] args) {
String str1 = "HelloWorld";
String str2 = "world";
// 示例1:区分大小写比较
// 比较 str1 的 "World"(索引5开始,长度5)和 str2 的 "world"(索引0开始,长度5)
boolean match1 = str1.regionMatches(5, str2, 0, 5);
System.out.println(match1); // false('W' vs 'w' 大小写不同)
// 示例2:忽略大小写比较
boolean match2 = str1.regionMatches(true, 5, str2, 0, 5);
System.out.println(match2); // true(忽略大小写后相等)
// 示例3:区域超出边界
boolean match3 = str1.regionMatches(0, str2, 0, 10); // str2 长度为5,区域超界
System.out.println(match3); // false
}
}
输出结果
false
true
false
通过 regionMatches() 方法,可以方便地比较字符串的部分区域,适用于需要验证子串匹配的场景(如判断文件后缀、提取特定格式的子串等)。