[英]Searching for one string in another string
Let's say I have String Table that have a few strings (like mother, father, son) and now in this String Table I want to find every word that contains string "th" for example. 假设我的字符串表有几个字符串(比如母亲,父亲,儿子),现在在这个字符串表中,我想找到包含字符串“th”的每个单词。
How should I do it? 我该怎么办? Method string.equals(string) won't help here.
方法string.equals(string)在这里没有帮助。
The following snippet should be instructive: 以下片段应具有指导意义:
String[] tests = {
"father",
"mammoth",
"thumb",
"xxx",
};
String fmt = "%8s%12s%12s%12s%12s%n";
System.out.format(fmt,
"String", "startsWith", "endsWith", "contains", "indexOf");
for (String test : tests) {
System.out.format(fmt, test,
test.startsWith("th"),
test.endsWith("th"),
test.contains("th"),
test.indexOf("th")
);
}
This prints: 这打印:
String startsWith endsWith contains indexOf
father false false true 2
mammoth false true true 5
thumb true false true 0
xxx false false false -1
boolean startsWith(String prefix)
boolean endsWith(String suffix)
boolean contains(CharSequence s)
true
if and only if this string contains the specified sequence of char values. true
。 int indexOf(String s)
-1
if there's no occurrence -1
如果没有发生 Here's an example of using indexOf
and lastIndexOf
with the startingFrom
argument to find all occurrences of a substring within a larger string, forward and backward. 下面是使用
indexOf
和lastIndexOf
以及startingFrom
参数来查找较大字符串(前向和后向)中所有子字符串的示例。
String text = "012ab567ab0123ab";
// finding all occurrences forward
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf("ab", i-1)) != -1; ) {
System.out.println(i);
} // prints "14", "8", "3"
If you know how to search a String
inside another String
, you would know how to loop in a String
table. 如果你知道如何寻找一个
String
另一里面String
,你会知道如何循环在一个String
表。 You could use indexOf
as someone else has suggested or you could use regex
if it more complex. 您可以像其他人建议的那样使用
indexOf
,或者如果它更复杂,您可以使用regex
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.