searching a character in a string
How can i search a character "开发者_如何学运维
in a string.
You can use string::find() function. visit here for more info
#include <string>
using namespace std;
int main ()
{
string str ("foo\"bar");
string str2 ("\"");
size_t found;
//you may want to do str.find('"') if you are only looking for one char.
found=str.find(str2);
}
it's very important to escape the " character inside defined strings.
The best you can do for finding a character in an unsorted string is a linear search:
for each index in the string:
if the character at that index matches the search criteria:
report the current index
report not found
There is, of course, a function for doing that already: std::string::find, which will return std::string::npos if the character is not found; otherwise, the function will return the index at which the character is first found. There are also variations of find like std::string::find_first_of, std::string::find_last_of, and their "not_of" variants.
string::find()
Here is simple solution:
#include <string.h>
using namespace std;
int findChar(char c, string myString)
{
pos = myString.find(c); // Find position in the string (to access myString[pos])
return int(pos);
}
This is the solution that doesn't have any depedency with library in C++
char * foo = "abcdefg";
char cf = 'e'; // Char to find
int f = 0; while (*(foo + f++) != cf); // f is 5
精彩评论