【问题标题】:How to find the first index of the words?如何找到单词的第一个索引?
【发布时间】:2013-02-28 14:01:54
【问题描述】:

我使用下面的代码

 String fulltext = "I would like to create some text and i dont know what creater34r3, ";
    String subtext = "create";

    int ind = -1;
            do {
                ind = fulltext.indexOf(subtext, ind + subtext.length());

            } while (ind != -1);

结果,我找到了单词的第一个索引:

create creater34r3

但我只需要找到单词 create

的第一个索引

怎么做?帮助

【问题讨论】:

  • 你刚刚删除了你的问题并重新发布了吗?为什么?
  • 一开始我更容易提出想法
  • 您要查找“创建”吗? “创造。”? “创建”(在字符串的末尾)?
  • 例如,当您在笔记本上写字并涂抹时 - 您拉了一块?

标签: java string substring


【解决方案1】:

如果我理解您在字符串中查找整个单词的要求,如果它们存在,那么如何:

    String fulltext = "I would like to create some text and i dont know what creater34r3, ";
    String subtext = "create";
    Pattern pattern = Pattern.compile("\\b(" + subtext + ")\\b");
    Matcher matcher = pattern.matcher(fulltext);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

输出将是create

但我突然想到您需要实际的索引 - 如果需要,您可以将其添加到 while 块中:

      int start = matcher.start();
      int end = matcher.end();

【讨论】:

  • 谢谢你帮助我。我想问你,我有subtext = "create s";我怎么得到subtext = "create some"; or subtext = "create";??
  • @MaxUsanin - 所以你想要“创建”或“创建一些”的索引?对吗?
  • 不,与帖子无关。我有一些子字符串,例如“create s”或“create som”或“create so”,如果“create some” - 没关系,我需要由整个单词组成的子字符串
  • 这个怎么样? Pattern.compile("\\b(" + subtext + "\\p{Alnum}+)");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多