2013-11-10 7 views
5

Questo codice che ho scritto loop attraverso una stringa char per char. Quello che voglio è passare attraverso una stringa parola per parola. Ecco il mio codice.Come eseguire il ciclo di una stringa per spazio? Come faccio a sapere il numero indice della parola che attualmente sono nella stringa?

string a; // already declared 
    // c is string array 
for (i=0;i<b;i++) { 
    if (strcmp (c[i],a[i]) == 0) { 
     // do something 
     } 
    } 
+3

Non è necessario 'strcmp' per confrontare i caratteri. Basta usare 'c [i] == a [i]'. – deepmax

+0

voglio confrontare stringhe non caratteri, è per questo che vorrei scorrere l'intera stringa parola per parola. – amian

risposta

10

È possibile utilizzare stringhe-stream:

string a = "hello my name is joe"; 
stringstream s(a); 
string word; 
// vector<string> c = ... ; 

for (int i = 0; s >> word; i++) 
{ 
    if (word == c[i]) 
    { 
     // do something 
    } 
} 

Se si desidera avere la capacità di andare davanti e dietro a parole, è necessario memorizzare in un array, quindi questo secondo codice è utile per questo:

string a = "hello my name is joe"; 
vector<string> c = {"hello","my","name","is","joe"}; 
string word; 
vector<string> words; 

for (stringstream s(a); s >> word;) 
    words.push_back(word); 

for (int i=0; i<words.size(); i++) 
{ 
    if (words[i] == c[i]) 
    { 
     // do something 
    } 
} 
+0

@M M. come posso ottenere il numero di indice della parola "I am on" durante il periodo di confronto? – amian

+1

mantieni un conteggio e incrementalo ogni iterazione del ciclo – Teeknow

+0

@Frontenderman cosa succede se voglio tornare indietro di qualche posizione nella stringa? – amian

0

Controllare questo:

#include <stdio.h> 
#include <iostream> 

using namespace std; 

void sort(int *,int); 

int word_size(char * in, int length) 
{ 
    int size = 0; 
    if(!strcmp(in,"")) 
     size = 1; 

    for(int i =0 ;i<length;i++) 
    { 
     if(in[i] == ' ') 
      size ++; 
    } 

    return size; 
} 

int get_word_size(char * in,int length, int index) 
{ 
    int word_num = 0; 
    int size = 0; 

    for(int i = 0;i<length;i++) 
    { 
     if(in[i] == ' ') 
      word_num++; 
     else if(word_num == index) 
     { 
      size++; 
     } 
    } 
    return size; 
} 

char * get_word(char * in,int length,int index) 
{ 
    char * result = new char[get_word_size(in,length,index)]; 
    int k = 0; 
    int word_num = 0; 

    for(int i = 0;i<length;i++) 
    { 
     if(in[i] == ' ') 
      word_num++; 
     else if(word_num == index) 
     { 
      result[k] = in[i]; 
      k++; 
     } 
    } 

    return result; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    char * x = "Hello this is my name"; 


    char * y = "byebye that was your name"; 



    char * outChar = get_word(x,21,3); 
    outChar[get_word_size(x,21,2)] = '\0'; 
    cout << outChar; 

    int a; 
    cin>>a; 
    return 0; 
} 

Appena testato ...

Problemi correlati