这篇Java教程基于JDK1.8。教程中的示例和实践不会使用未来发行版中的优化建议。
字符串和字符串子串的比较
String 类提供了许多方法来比较字符串和子串。下表列出了这些方法:
方法 | 描述 |
---|---|
boolean endsWith(String suffix) boolean startsWith(String prefix) | 如果字符串以给定的suffix开头或结尾,则返回true |
boolean startsWith(String prefix, int offset) | 以下标offset开头的字符串,如果前缀是prefix,则返回true |
int compareTo(String anotherString) | 按词法比较两个字符串。返回整数来表示当前字符串比参数大(结果大于0),与参数相等(结果等于0),比参数小(结果小于0) |
int compareToIgnoreCase(String str) | 同int compareTo(String anotherString),但忽略大小写 |
boolean equals(Object anObject) | 当参数是个String对象并且包含的字符序列与当前对象一致则返回true |
boolean equalsIgnoreCase(String anotherString) | 同boolean equals(Object anObject) ,忽略大小写 |
boolean regionMatches(int toffset, String other, int ooffset, int len) | 测试此字符串的指定区域是否与字符串参数的指定区域匹配。区域的长度为len,从这个字符串的索引toffset开始,另一个字符串的索引从ooffset开始。 |
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) | 同上,忽略大小写 |
boolean matches(String regex) | 测试该字符串是否匹配给定的正则表达式 |
下面的程序,使用regionMatches方法来在字符串中搜索指定字符串:
public class RegionMatchesDemo {
public static void main(String[] args) {
String searchMe = "Green Eggs and Ham";
String findMe = "Eggs";
int searchMeLength = searchMe.length();
int findMeLength = findMe.length();
boolean foundIt = false;
for (int i = 0;
i <= (searchMeLength - findMeLength);
i++) {
if (searchMe.regionMatches(i, findMe, 0, findMeLength)) {
foundIt = true;
System.out.println(searchMe.substring(i, i + findMeLength));
break;
}
}
if (!foundIt)
System.out.println("No match found.");
}
}
程序输出
Eggs
程序一步一个字符地遍历searchMe引用的字符串。对每个字符,程序会调用regionMatches方法来判断当前子串是否以该字符开头并匹配程序正在找的字符串。