在另一个字符串中搜索一个字符串

时间:2010-05-30 20:11:40

标签: java string search

假设我有一些字符串表,有几个字符串(如母亲,父亲,儿子),现在在这个字符串表中我想找到包含字符串“th”的每个单词。

我该怎么办?方法string.equals(string)在这里没有帮助。

3 个答案:

答案 0 :(得分:11)

以下代码段应具有指导意义:

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")
    );
}

打印:

  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

字符串API链接


查找所有事件的索引

以下是使用indexOflastIndexOfstartingFrom参数一起使用的示例,以查找较大字符串(前向和后向)中所有子字符串的出现。

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"

答案 1 :(得分:8)

使用containsindexOf方法,具体取决于您是否需要这个位置。

答案 2 :(得分:1)

如果您知道如何搜索另一个String内的String,您就会知道如何在String表中循环。您可以像其他人建议的那样使用indexOf,或者如果它更复杂,您可以使用regex