【问题标题】:Finding any words in a string with its indexes查找字符串中的任何单词及其索引
【发布时间】:2011-11-05 23:40:20
【问题描述】:

假设我有字符串:

-dog--cat--d--

我想从该字符串中查找所有单词,并且长度应大于 1。

但更重要的是,我想知道每个单词的第一个和最后一个索引。

我该怎么做?

我正在考虑创建结构。它可以存储一些数据(索引开始和停止,单词,长度等)

但我真的不知道如何找到任何方法来获取这些单词。

到目前为止,我只创建了存储值 0 和 1 的数组(如果元素为“-”则为 0,否则为 1)。 有谁能够帮助我? :)

【问题讨论】:

  • 你如何定义“单词”? 2 个或更多 Unicode 字母的序列?
  • A suffix tree 符合我理解的您的要求,可能与您的意思有所不同。
  • @MarkByers,我在“-”之间定义了序列 Unicode 字母,例如。 "-dog-" => dog

标签: c# algorithm word


【解决方案1】:

您可以使用正则表达式@"\p{L}{2,}" 查找2个或更多连续字母:

foreach (Match match in Regex.Matches(s, @"\p{L}{2,}")) {
    // match.Index, match.Value, etc..
}

【讨论】:

  • 将其更改为 @"\p{L}{1,}" 以使 d 也显示出来,或者只是 @"\w+" 以选择单词
【解决方案2】:

您可能最好使用 正则表达式 过滤掉任何非字母并返回单词数组

      String sourcestring = "-dog--cat--d--";
      Regex re = new Regex(@"\w+");
      MatchCollection mc = re.Matches(sourcestring);
      int mIdx=0;
      foreach (Match m in mc)
       {
        for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
          {
            Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
          }
        mIdx++;
      }

【讨论】:

  • I would like to know first and last index of each of the words
  • @L.B 感谢您的反对,因为您可以使用 System.Text.RegularExpressions.Match 类过滤单词并获取索引等信息...
猜你喜欢
  • 2018-11-20
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多