java - 如何查找一个字符串在另一个字符串中的出现情况,而该字符串没有嵌入到另一个单词中?

标签 java

我正在尝试创建一个静态方法“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 ) ); 
} 

最佳答案

类似这样的事情:

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

关于java - 如何查找一个字符串在另一个字符串中的出现情况,而该字符串没有嵌入到另一个单词中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600009/

相关文章:

java - 为 Java 应用程序创建安装程序

java - 如果类位于包中,如何从命令行运行 JUnit 测试?

java - m_coloring 的蒙特卡罗估计

java - 压缩会提高性能吗?

java - 规范路径不起作用

java - Log4j2 RollingFileManager OnStartupTriggeringPolicy 从不在启动时滚动文件

java - Java 中的 JSON 对象有问题吗?

java - 复杂 Web 应用程序上的 ConversionInputException

java - 在 Eclipse 中导出多个 jar

java - 如果没有@EnableMVC,这段代码如何工作?