The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The String
class has a number of methods for comparing strings and portions of strings.String
类有许多方法用于比较字符串和字符串的一部分。The following table lists these methods.下表列出了这些方法。
boolean endsWith(String suffix) |
true if this string ends with or begins with the substring specified as an argument to the method.true 。 |
boolean startsWith(String prefix, int offset) |
offset , and returns true if it begins with the substring specified as an argument.offset 开始的字符串,如果以指定为参数的子字符串开始,则返回true 。 |
int compareTo(String anotherString) |
|
int compareToIgnoreCase(String str) |
|
boolean equals(Object anObject) |
true if and only if the argument is a String object that represents the same sequence of characters as this object.String 对象时,返回true 。 |
boolean equalsIgnoreCase(String anotherString) |
true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.String 对象时返回true ,忽略大小写差异。 |
boolean regionMatches(int toffset, String other, int ooffset, int len) |
|
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) |
|
boolean matches(String regex) |
The following program, 以下程序RegionMatchesDemo
, uses the regionMatches
method to search for a string within another string:RegionMatchesDemo
使用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."); } }
The output from this program is 这个程序的输出是Eggs
.Eggs
。
The program steps through the string referred to by 程序一步一个字符地遍历searchMe
one character at a time.searchMe
引用的字符串。For each character, the program calls the regionMatches method to determine whether the substring beginning with the current character matches the string the program is looking for.对于每个字符,程序调用regionMatches
方法来确定以当前字符开头的子字符串是否与程序正在查找的字符串匹配。