查找字符串中的任何单词及其索引

发布于 2024-12-13 21:51:24 字数 286 浏览 3 评论 0原文

假设我有字符串:

-dog--cat--d--

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

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

我怎么能这么做呢?

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

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

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

Let's say that I have string:

-dog--cat--d--

I would like to find all words from that string, and length should be greater than 1.

But what is more, I would like to know first and last index of each of the words.

How could I do that?

I was thinking about creating struct. It could store some data(index start and stop, words, length, etc.)

But I really do not know how to find out any way to get that words.

So far I only created array storing valuese 0 and 1 (if element is '-' then 0 else 1).
Can anybody help me? :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陈年往事 2024-12-20 21:51:24

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

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

You can use the regular expression @"\p{L}{2,}" to find 2 or more consecutive letters:

foreach (Match match in Regex.Matches(s, @"\p{L}{2,}")) {
    // match.Index, match.Value, etc..
}
顾北清歌寒 2024-12-20 21:51:24

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

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

You would probably be best using Regular Expressions to filter out any non-letters and return an array of words

      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++;
      }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文