Find the index of a special character in a string in C ++

I want to know if there is any standard function in visual stodio 2010, C ++, which takes a character and returns an index in a special string if it exists in the string. Tnx

+4
source share
4 answers

You can use std::strchr .

If you have a C string:

 const char *s = "hello, weird + char."; strchr(s, '+'); // will return 13, which is '+' position within string 

If you have an instance of std::string :

 std::string s = "hello, weird + char."; strchr(s.c_str(), '+'); // 13! 

With std::string you can also find the search method you are looking for.

+4
source

strchr or std::string::find , depending on the type of string?

+3
source

strchr () returns a pointer to a character in a 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 
+2
source
 #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; } 
0
source

All Articles