【问题标题】:How to search word by word in android如何在android中逐字搜索
【发布时间】:2012-08-05 05:37:43
【问题描述】:

如何在字符串中搜索单词?

例如

String text = "Samsung Galaxy S Two";

如果我使用text.contains("???");

它会得到任何相关的字母,即使它不是一个合适的词,例如来自“Galaxy”的“axy”。

有什么建议或解决方案吗?

【问题讨论】:

标签: java android string search


【解决方案1】:
List<String> tokens = new ArrayList<String>();

String text = "Samsung Galaxy S Two";
StringTokenizer st = new StringTokenizer(text);

    //("---- Split by space ------");
    while (st.hasMoreElements()) {
        tokens.add(st.nextElement().toString());
    }

    String search = "axy";
    for(int i=0;i<tokens.size();i++)
    {
        if(tokens.get(i).contains(search))
        {
            System.out.println("Word is "+tokens.get(i));
            break;//=====> Remove Break if you want to continue searching all the words which contains `axy`
        }
    }

output====>Galaxy

【讨论】:

    【解决方案2】:

    对于最简单的用法,您可以使用 StringTokenizer 看看这个链接。 http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html

    要使用正则表达式,请查看 android 中的模式。 http://developer.android.com/reference/java/util/regex/Pattern.html

    【讨论】:

      【解决方案3】:

      使用indexOf:

      int i= string.indexOf('1'); 
      

      substring

      String s=string.substring("koko",0,1);
      

      【讨论】:

        【解决方案4】:

        试试这个..

        String string = "madam, i am Adam";
        

        // 字符

        // First occurrence of a c
        int index = string.indexOf('a');    // 1
        
        // Last occurrence
        index = string.lastIndexOf('a');    // 14
        
        // Not found
        index = string.lastIndexOf('z');    // -1
        

        // 子字符串

        // First occurrence
        index = string.indexOf("dam");      // 2
        
        // Last occurrence
        index = string.lastIndexOf("dam");  // 13
        
        // Not found
        index = string.lastIndexOf("z");    // -1
        

        【讨论】:

          【解决方案5】:

          我知道这是一个老问题,但我写在这里是为了帮助下一个需要帮助的人。

          您可以使用匹配项

          String str = "Hello, this is a trial text";
          str1 = str.toLowerCase();
          if(str1.matches(".*trial.*")) //this will search for the word "trial" in str1
          {
              //Your Code
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多