【问题标题】:Find the index of a special character in string in C++在 C++ 中查找字符串中特殊字符的索引
【发布时间】:2010-12-07 12:03:22
【问题描述】:

我想知道visual stodio 2010,C++中是否有任何标准函数,它接受一个字符,并在特殊字符串中返回它的索引,如果它存在于字符串中。 天呐

【问题讨论】:

    标签: c++ string visual-studio-2010 visual-c++


    【解决方案1】:

    您可以使用std::strchr

    如果你有类似 C 的字符串:

    const char *s = "hello, weird + char.";
    strchr(s, '+'); // will return 13, which is '+' position within string
    

    如果您有std::string 实例:

    std::string s = "hello, weird + char.";
    strchr(s.c_str(), '+'); // 13!
    

    使用std::string,您还可以在其上找到您要查找的角色的方法。

    【讨论】:

    • 对不起,问题出在我的测试文件上,我使用了 find 方法。 'MyIndex=MyString.find('.');' Tnx
    【解决方案2】:

    strchrstd::string::find,取决于字符串的类型?

    【讨论】:

    • @rain: std::wstringstd::string 只是 std::basic_string<> 的特化,它们提供的方法完全相同...
    【解决方案3】:

    strchr() 返回一个指向字符串中字符的指针。

    const char *s = "hello, weird + char."; 
    char *pc = strchr(s, '+'); // returns a pointer to '+' in the string
    int idx = pc - s; // idx 13, which is '+' position within string 
    

    【讨论】:

      【解决方案4】:
      #include <iostream>
      #include <string>
      #include <algorithm>
      
      using namespace std;
      
      int main() {
          string text = "this is a sample string";
          string target = "sample";
      
          int idx = text.find(target);
      
          if (idx!=string::npos) {
              cout << "find at index: " << idx << endl;
          } else {
              cout << "not found" << endl;
          }
      
          return 0;
      }
      

      【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多