【问题标题】:Search a word in java?在java中搜索一个单词?
【发布时间】:2013-09-17 22:39:51
【问题描述】:

我有一个String 喜欢,

 String test = "voiceemailchat";
 String find = "chat";

我必须检查新单词是否已经存在于现有单词中。

条件看起来像,

if(test has find)
      //go something
else
      //go somethig

在java中是否可以?

【问题讨论】:

  • 这不是一个愚蠢的问题,只是看起来你没有尝试。
  • 抱歉问了一个简单的问题。我标记了这个问题。我意识到我的错误。
  • 这不是简单,只是看起来你没有尝试。老实说,-8 相当苛刻。习惯于阅读 JavaDocs。在其中查找字符串,看看可以做什么。我刚开始的时候从来没有这样做过,掌握它会产生巨大的影响。

标签: java string


【解决方案1】:

执行以下代码。如果您有大型数据文件或字符串,请使用正则表达式。这是最好的。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "voiceemailchat";
      String pattern = "chat";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found the value");
      } else {
         System.out.println("NO MATCH");
      }
   }
}

【讨论】:

    【解决方案2】:

    作为第一步 始终查看 Javadocs。对于String,点击here

    您可以使用以下任何一种方法:containsindexOf

    【讨论】:

      【解决方案3】:

      试试这个String#indexOf()

      if(test.indexOf(find)!=-1){
         ... // value is found
      }
      

      【讨论】:

        【解决方案4】:

        怎么样——

        if(test.indexof(find)>-1){
          ... // found
        }
        

        【讨论】:

          【解决方案5】:

          是的,有可能:

          String test = "voiceemailchat";
          String find = "chat";
          
          if(test.contains(find)) {
              //string found
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-17
            • 2013-12-18
            • 2017-03-30
            • 2014-03-23
            • 1970-01-01
            • 1970-01-01
            • 2012-12-16
            • 2011-09-13
            相关资源
            最近更新 更多