I'm trying to split an entry of the following type:
1444771699,Andre Alves,SAQUE,-500.00,,200
I'm trying to use strtok
, but it ignores empty space. Any idea how to split the string without ignoring the space?
I'm trying to split an entry of the following type:
1444771699,Andre Alves,SAQUE,-500.00,,200
I'm trying to use strtok
, but it ignores empty space. Any idea how to split the string without ignoring the space?
The strtok method, used to break a string, after passing its string a single time per parameter, just put NULL ou 0
in the first parameter, so the method will return the parts of the string. Use string.h
char *buff = "minha string com espaço";
char *word = strtok(buff," ");
int x=0;
while(word){
puts(word);
word = strtok(NULL, " ");
x++;
}
The strtok
function separates a string into "chunks", or tokens
, according to some used expression.
Function prototype: char* strtok(char* str, const char* delimiters);
So a simple solution to your problem would be something like:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
char string[] = "1444771699,Andre Alves,SAQUE,-500.00,,200";
printf("String: %s\n", string);
char* token;
token = strtok(string, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
Considering your entry as 1444771699,Andre Alves,SAQUE,-500.00,,200
, executing the above code will result in the output below < 1444771699
Andre Alves
SAQUE
-500.00
200
You can then allocate the output below in an array of strings if needed according to your application.
You can format the character string by character.
Example:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main() {
string s = "1444771699,Andre Alves,SAQUE,-500.00,,200";
int qtd = 1;
printf("string %d: ", qtd);
for (int i = 0; i < s.length(); i++)
if ( s[i] != ',')
printf("%c", s[i]);
else if ( s[i] == ',') {
qtd++;
printf("\nstring %d: ", qtd);
}
return 0;
}
I assume the problem is empty fields, which strtok()
does not recognize. In Linux, we have the function strsep()
, which was created precisely to solve the limitation of strtok()
:
#include <string.h>
char *strsep(char **stringp, const char *delim);