【问题标题】:How to find occurrence of a string in another string where it's not embedded into another word?如何在未嵌入另一个单词的另一个字符串中找到一个字符串的出现?
【发布时间】:2014-10-28 10:55:27
【问题描述】:

我正在尝试创建一个静态方法“indexOfKeyword”并返回一个 indexOf 字符串,其中该字符串未嵌入到另一个单词中。如果没有这种情况,它将返回 -1。

例如,

String s = "In Florida, snowshoes generate no interest.";
String keyword = "no";

这将返回 31。

我认为唯一的问题不是找到下一次出现的字符串关键字。到目前为止我所拥有的是:

public static int indexOfKeyword( String s, String keyword )
{

s = s.toLowerCase();
keyword = keyword.toLowerCase();


int startIdx = s.indexOf( keyword );



while ( startIdx >= 0 )
{

String before = " ";
String after = " ";

if ( startIdx > 0 ){

     before = s.substring( startIdx - 1 , startIdx);
 }


int endIdx = startIdx;


 if ( endIdx < s.length() ){

     after = s.substring( startIdx + keyword.length() , startIdx + keyword.length() + 1);
 }


if ( !(before.compareTo("a") >= 0 && before.compareTo("z") <= 0 && after.compareTo("a") >= 0 &&     after.compareTo("z") <= 0)){
  return startIdx;
}




startIdx = 
   /* expression using 2-input indexOf for the start of the next occurrence */

}


  return -1;
}


 public static void main( String[] args )  
 { 
 // ... and test it here 
String s = ""; 
String keyword = ""; 

System.out.println( indexOfKeyword( s, keyword ) ); 
} 

【问题讨论】:

  • 感谢大家的回答,但我忘了提到我正在尝试使用佛罗里达示例制作静态方法“indexOfKeyword”根本行不通

标签: java


【解决方案1】:

类似这样的:

String input = "In Florida, snowshoes generate no interest.";
String pattern = "\\bno\\b";
Matcher matcher = Pattern.compile(pattern).matcher(input);

return matcher.find() ? matcher.start() : -1;

没有嵌入另一个单词的字符串不一定用空格分隔。它可以是逗号、句点、字符串的开头等。

上述解决方案使用正则表达式单词边界(\b)来给出正确的解决方案。


如果您的关键字有可能包含在正则表达式中使用时具有特殊含义的字符,您可能需要先对其进行转义:

String pattern = "\\b" + Pattern.quote(keyword) + "\\b";

所以一个完整的方法实现可能如下所示:

public static int indexOfKeyword(String s, String keyword) {
    String pattern = "\\b" + Pattern.quote(keyword) + "\\b";
    Matcher matcher = Pattern.compile(pattern).matcher(s);

    return matcher.find() ? matcher.start() : -1;
}

【讨论】:

  • 值得向他展示如何将他的关键字转义为正则表达式模式
  • @KeithNicholas 感谢您的帮助!
  • +1 我不得不说我特别喜欢 return 语句,它巧妙地调用了 find(),它也 mutates 匹配器,允许立即调用 start() -线。
猜你喜欢
  • 2021-01-22
  • 2016-07-27
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 2011-03-25
  • 1970-01-01
相关资源
最近更新 更多