在C ++中查找字符串中特殊字符的索引

时间:2010-12-07 12:03:23

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

我想知道Visual Studio 2010中是否有任何标准函数,C ++,它接受一个字符,如果它存在于字符串中,则返回特殊字符串中的索引。 Tnxp>

4 个答案:

答案 0 :(得分:4)

您可以使用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,您还可以使用方法找到您要查找的字符。

答案 1 :(得分:3)

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

答案 2 :(得分:2)

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 

答案 3 :(得分:0)

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