2017-10-20 2 views
-2

Ich versuche, ein Zeichen zu teilen * basierend auf einem Begrenzungszeichen verschachtelte Vektoren jedoch das letzte Wort des char * scheint nicht zu dem> Vektor hinzugefügt wirdgeteilte Implementierung unter Verwendung von Vektoren und char *

vector<vector<char>> split(char* word, const char de){ 
    vector<vector<char>> words; 
    vector<char> c_word; 
    while(*word){ 
     if(*word == de){ 
      words.push_back(c_word); 
      c_word.clear(); 
      word++; 
      continue; 
     } 
     c_word.push_back(*word); 
     word++; 
    } 
    return words; 
} 

Beispiel Nutzung:

int main() { 
    char *let = "Hello world!"; 

    vector<vector<char>> words = split(let, ' '); 
    for(int x = 0;x < words.size();x++){ 
     for(int y = 0;y < words[x].size();y++){ 
      cout << words[x][y]; 
     } 
     cout << endl; 
    } 
} 

dieses nur Hallo

+0

können Sie einen Code mit Eingabe bereitstellen, damit man es ausprobieren kann? www.ideone.com –

+0

Gibt es einen Grund, warum Sie 'std :: vector >' anstelle von 'std :: vector ' verwenden? Und 'char *' anstelle von 'std :: string'? –

+0

Wenn das letzte Zeichen nicht das Trennzeichen ist, haben Sie immer noch ein Wort in 'c_word', wenn die Schleife beendet ist. –

Antwort

-2

Für alle fragen würde drucken sonst wie diese Implementierung zu tun char * anstelle von String. Was mein Code fehlt eine letzte Add von c_word zu Worten ist, da die während schon vorbei ist, wenn es den Nullabschluss erreicht und fügen Sie nicht das letzte Wort, das ist der feste Code:

vector<vector<char>> split(char* word, const char de){ 
    vector<vector<char>> words; 
    vector<char> c_word; 
    while(*word){ 
     if(*word == de){ 
      words.push_back(c_word); 
      c_word.clear(); 
      word++; 
      continue; 
     } 
     c_word.push_back(*word); 
     word++; 
    } 
    words.push_back(c_word); 
    return words; 
} 
-1

Hier ist ein Voll funktionsfähiger Code mit mehreren Delimetern

vector<vector<char>> split(char* word, const char de) { 
    vector<vector<char>> words; 
    vector<char> c_word; 
    int index = 0; 
    int j = 0; 
    char *temp = word; 
    int numspaces = 0; 
    while (*word) { 
     if (*word == de) { 
      words.push_back(c_word); 
      c_word.clear(); 
      word++; 
      j = index; 
      numspaces++; 
     } 
     index++; 
     c_word.push_back(*word); 
     word++; 
    } 
    j +=numspaces; 
    char *sub = &temp[j]; 
    c_word.clear(); 
    while (*sub) 
    { 
     c_word.push_back(*sub); 
     sub++; 
    } 
    words.push_back(c_word); 
    return words; 
} 
void main() 
{ 
    vector<vector<char>> result = split("Hello World! Ahmed Saleh", ' '); 

} 
Verwandte Themen