How can I split a string by semicolon and take the value of each position after the while?

Asked

Viewed 88 times

0

How can I make one split of a string per semicolon and take the value of each position after the while ?

Example:

result[0] //casa result[1] //carro

My code:

char str[] ="test;car;bar;mouse";
        char * pch;

        string result;

        pch = strtok (str,";");
        while (pch != NULL)
        {

          result += pch;
          printf ("%s\n",pch);
          pch = strtok (NULL, ";");
        }



     printf("value by position 0\n", result[0]);
  • But it’s not C++? Why is it programmed in C?

  • Batatei putting C++. Thanks friend.

2 answers

1

Can declare a multi char array result[5][10] where there are 5 lines of strings that can have a maximum length of 10 characters in each line. This is a very siples example, can also dynamically make the memory allocation, do char** result and realloc\ malloc as it needs more space.

Here’s an example of how you could solve your problem:

char str[] ="test;car;bar;mouse";
char * pch;
pch = strtok (str,";");
char result[5][10];//declara multi array com 5 linhas e 10 caracteres maximo por linha
int i=0;
while (pch != NULL)
{
     strcpy(result[i++], pch);// a cada linha envia a String pch para result
     printf ("%s\n",pch);
     pch = strtok (NULL, ";");
}

printf("value by position 0 %s\n", result[0]);
  • That’s what I’ve been wanting to do, thank you very much Fábio.

0


This code is not C++, it’s C, if you think you’re learning C++, you’re wrong, just because it compiles in C++ doesn’t mean it’s C++. If you want to do in C++ you have the option here which is much safer because the library already provides adequate mechanisms:

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream texto("test;car;bar;mouse");
    string token;    
    while (getline(texto, token, ';')) {
        cout << token << endl;
        strings.push_back(token);
    }
    cout << "value by position 0 " << strings[0];
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.