在C+中查找字符串中特殊字符的索引+; 我想知道Visual Studio 2010,C++中是否有任何标准函数,它取一个字符,如果它存在于字符串中,则返回它在特殊字符串中的索引。 Tnx或,取决于字符串的类型,您可以使用
如果您有一个C类字符串:在C+中查找字符串中特殊字符的索引+; 我想知道Visual Studio 2010,C++中是否有任何标准函数,它取一个字符,如果它存在于字符串中,则返回它在特殊字符串中的索引。 Tnx或,取决于字符串的类型,您可以使用,c++,string,visual-studio-2010,visual-c++,C++,String,Visual Studio 2010,Visual C++,如果您有一个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还可以在其上找到要查找的字符的方法。s
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()返回指向字符串中字符的指针
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
#包括
#包括
#包括
使用名称空间std;
int main(){
string text=“这是一个示例字符串”;
字符串target=“sample”;
int idx=text.find(目标);
if(idx!=string::npos){
很抱歉,问题出在我的测试文件上,我使用了find方法。'MyIndex=MyString.find('.');'Tnx@rain:std::wstring
和std::string
只是std::basic_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;
}