2010-05-09 6 views

Répondre

2

Le mieux que vous pouvez faire pour trouver un caractère dans une chaîne non triée est une recherche linéaire:

for each index in the string: 
     if the character at that index matches the search criteria: 
       report the current index 
report not found 

Il est, bien sûr, une fonction pour le faire déjà: std::string::find, qui retournera std::string::npos si la le caractère n'est pas trouvé; sinon, la fonction retournera l'index où le caractère a été trouvé pour la première fois. Il existe également des variantes de find comme std::string::find_first_of, std::string::find_last_of, et leurs variantes "not_of".

3

Vous pouvez utiliser la fonction string :: find(). visitez here pour plus d'informations

#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); 
} 

il est très important d'échapper à la "caractère à l'intérieur des chaînes définies

+0

Ou au lieu d'allouer une nouvelle chaîne pour tenir '" \ "" 'vous pouvez utiliser' string :: find() 'avec le caractère unique'' "''. –

+0

@wintermute thankyou – msemelman

2

Voici une solution simple:.

#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); 
} 
0

Ceci est la solution que n'a pas toute déchéance avec bibliothèque en C++

char * foo = "abcdefg"; 

char cf = 'e'; // Char to find 

int f = 0; while (*(foo + f++) != cf); // f is 5 
Questions connexes