【发布时间】:2010-12-07 12:03:22
【问题描述】:
我想知道visual stodio 2010,C++中是否有任何标准函数,它接受一个字符,并在特殊字符串中返回它的索引,如果它存在于字符串中。 天呐
【问题讨论】:
标签: c++ string visual-studio-2010 visual-c++
我想知道visual stodio 2010,C++中是否有任何标准函数,它接受一个字符,并在特殊字符串中返回它的索引,如果它存在于字符串中。 天呐
【问题讨论】:
标签: c++ string visual-studio-2010 visual-c++
您可以使用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,您还可以在其上找到您要查找的角色的方法。
【讨论】:
strchr 或std::string::find,取决于字符串的类型?
【讨论】:
std::wstring 和 std::string 只是 std::basic_string<> 的特化,它们提供的方法完全相同...
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;
}
【讨论】:
foo.cpp:13:12: warning: comparison of integer expressions of different signedness。也许使用size_t idx,另见Why is "using namespace std;" considered bad practice?