【问题标题】:CString find the last entryCString 找到最后一个条目
【发布时间】:2012-08-12 14:38:33
【问题描述】:

我有两个CString s1 和CString s2。我需要在 s1 中找到最后一个条目 s2。 我可以在 CString 中找到任何方法,例如在 C# LastIndexOf 中。 我是 C++ 中的菜鸟。提前致谢。

【问题讨论】:

  • @geminiCoder:c 字符串只是一个字符数组,但 CString 是 MSVS 特定的 C++ 类。
  • 感谢您的支持。 @goldilocks

标签: c++ mfc


【解决方案1】:

CString 没有这个功能。你必须自己写,例如

int LastIndexOf(const CString& s1, const CString& s2)
  {
  int found = -1;
  int next_pos = 0;
  for (;;)
    {
    next_pos = s1.Find(s2, next_pos);
    if (next_pos == -1)
      return found;

    found = next_pos;
    };
  }

一种更优化的算法会首先反转字符串,我将其留作练习。

【讨论】:

    【解决方案2】:

    您不需要实现自我功能。 std 提供了一个函数:std::string::find_last_of。 例如:

    std::string str("c:\windows\winhelp.exe");
    unsigned found = str.find_last_of("/\\");
    std::cout << " path: " << str.substr(0,found) << '\n';
    std::cout << " file: " << str.substr(found+1) << '\n';
    
    
    path: c:\windows
    file: winhelp.exe
    

    【讨论】:

      【解决方案3】:

      我采用了 Andrey 的答案(为了增加 next_pos,没有它似乎会导致无限循环)。 aaand,由于我还没有足够的声望(无法评论),我将其作为单独的答案发布:

      int LastIndexOf(const CString& s1, const CString& s2)
      {
          int start = s1.Find(s2, 0);
      
          if (start >= 0) 
          {
              while (start < s1.GetLength()) 
              {
                  int idx = s1.Find(s2, start+1); 
                  if (idx >= 0) 
                      start = idx; 
                  else 
                      break; 
              }
          }
      
          return start;
      }
      

      【讨论】:

        【解决方案4】:

        没有CString 方法可以直接解决您的问题。但是,您可以使用CString::ReverseFind + _tcsncmp 的组合首先定位子字符串最后一个字符的下一个匹配项,如果找到,则从那里比较整个子字符串。

        【讨论】:

          【解决方案5】:

          CString 我认为是“Microsoft 基础类库”的一部分,不是标准 C++。 这里有一个包含方法的参考:

          http://msdn.microsoft.com/en-us/library/aa315043%28v=vs.60%29.aspx

          我没有看到任何东西可以直接将其转换为 std::string(它有更多的方法),但它可能也不是那么难(搜索“CString to std::string”然后你'会找到一些东西)。

          尽管它们可能相关,但不要将其与 c 字符串混淆,c 字符串是标准 C++ 中包含的标准 C 中的 chars 数组。

          【讨论】:

            猜你喜欢
            • 2011-01-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-11
            • 2014-10-22
            • 2015-06-09
            • 1970-01-01
            相关资源
            最近更新 更多