简体   繁体   English

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

[英]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

String API links 字符串API链接

  • boolean startsWith(String prefix)
    • Tests if this string starts with the specified prefix. 测试此字符串是否以指定的前缀开头。
  • boolean endsWith(String suffix)
    • Tests if this string ends with the specified suffix. 测试此字符串是否以指定的后缀结尾。
  • boolean contains(CharSequence s)
    • Returns true if and only if this string contains the specified sequence of char values. 当且仅当此字符串包含指定的char值序列时,才返回true
  • int indexOf(String s)
    • Returns the index within this string of the first occurrence of the specified substring. 返回指定子字符串第一次出现的字符串中的索引。
      • -1 if there's no occurrence -1如果没有发生

Finding indices of all occurrences 查找所有事件的索引

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. 下面是使用indexOflastIndexOf以及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"

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM