Reputation: 403
I wanna know if there is any standard function in visual stodio 2010, C++, which takes a character, and returns the index of it in special string, if it is exist in the string. Tnx
Upvotes: 5
Views: 31248
Reputation: 181280
You can use std::strchr
.
If you have a C like string:
const char *s = "hello, weird + char.";
strchr(s, '+'); // will return 13, which is '+' position within string
If you have a std::string
instance:
std::string s = "hello, weird + char.";
strchr(s.c_str(), '+'); // 13!
With a std::string
you can also a method on it to find the character you are looking for.
Upvotes: 4
Reputation: 1771
#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;
}
Upvotes: 2
Reputation: 1797
strchr() returns a pointer to the character in the string.
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
Upvotes: 2