我想知道在Visual Studio 2010的C++中是否有任何标准函数,它可以接收一个字符,并返回该字符在特定字符串中的索引,如果该字符存在于该字符串中。 谢谢。
我想知道在Visual Studio 2010的C++中是否有任何标准函数,它可以接收一个字符,并返回该字符在特定字符串中的索引,如果该字符存在于该字符串中。 谢谢。
std::strchr
函数。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
,您还可以在其上调用一个方法来查找您要查找的字符。
strchr
或 std::string::find
来查找字符串中的字符。std::wstring
和std::string
只是std::basic_string<>
的特化版本,它们提供完全相同的方法... - Matthieu M.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
#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;
}