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

5

我想知道在Visual Studio 2010的C++中是否有任何标准函数,它可以接收一个字符,并返回该字符在特定字符串中的索引,如果该字符存在于该字符串中。 谢谢。

4个回答

5
你可以使用 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,您还可以在其上调用一个方法来查找您要查找的字符。


抱歉,问题出在我的测试文件上,我使用了查找方法。'MyIndex= MyString.find('.');' 谢谢。 - rain

3

@rain:std::wstringstd::string只是std::basic_string<>的特化版本,它们提供完全相同的方法... - Matthieu M.

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 

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

foo.cpp:13:12: 警告:比较不同符号的整数表达式。也许可以使用 size_t idx,并参考为什么被认为是不好的实践使用 using namespace std; - ggorlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接