比较字符串和字符串的部分

原文: https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

String类有许多用于比较字符串和字符串部分的方法。下表列出了这些方法。

Methods for Comparing Strings | 方法 | 描述 | | —- | —- | | boolean endsWith(String suffix) boolean startsWith(String prefix) | 如果此字符串以指定为方法参数的子字符串结束或以其开头,则返回true。 | | boolean startsWith(String prefix, int offset) | 考虑从索引offset开始的字符串,如果它以指定为参数的子字符串开头,则返回true。 | | int compareTo(String anotherString) | 按字典顺序比较两个字符串。返回一个整数,指示此字符串是否大于(结果是> 0),等于(结果是= 0)或小于(结果是< 0)参数。 | | int compareToIgnoreCase(String str) | 按字典顺序比较两个字符串,忽略大小写的差异。返回一个整数,指示此字符串是否大于(结果是> 0),等于(结果是= 0)或小于(结果是< 0)参数。 | | boolean equals(Object anObject) | 当且仅当参数是String对象时,返回true,该对象表示与此对象相同的字符序列。 | | boolean equalsIgnoreCase(String anotherString) | 当且仅当参数是String对象时,返回true,该对象表示与此对象相同的字符序列,忽略大小写的差异。 | | boolean regionMatches(int toffset, String other, int ooffset, int len) | Tests whether the specified region of this string matches the specified region of the String argument.区域长度为len,从该字符串的索引toffset开始,另一个字符串的ooffset。 | | boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) | Tests whether the specified region of this string matches the specified region of the String argument.区域长度为len,从该字符串的索引toffset开始,另一个字符串的ooffset。boolean 参数指示是否应忽略大小写;如果为 true,则在比较字符时忽略大小写。 | | boolean matches(String regex) | 测试此字符串是否与指定的正则表达式匹配。正则表达式在标题为“正则表达式”的课程中讨论。 |

以下程序RegionMatchesDemo使用regionMatches方法在另一个字符串中搜索字符串:

  1. public class RegionMatchesDemo {
  2. public static void main(String[] args) {
  3. String searchMe = "Green Eggs and Ham";
  4. String findMe = "Eggs";
  5. int searchMeLength = searchMe.length();
  6. int findMeLength = findMe.length();
  7. boolean foundIt = false;
  8. for (int i = 0;
  9. i <= (searchMeLength - findMeLength);
  10. i++) {
  11. if (searchMe.regionMatches(i, findMe, 0, findMeLength)) {
  12. foundIt = true;
  13. System.out.println(searchMe.substring(i, i + findMeLength));
  14. break;
  15. }
  16. }
  17. if (!foundIt)
  18. System.out.println("No match found.");
  19. }
  20. }

该程序的输出为Eggs

程序一次逐步执行searchMe引用的字符串。对于每个字符,程序调用 regionMatches 方法来确定以当前字符开头的子字符串是否与程序正在查找的字符串匹配。