aster94
September 23, 2019, 12:03am
1
I am writing a funcion to split string but the problem is that it "destroys" the original string
I am not able to make strtok_r works
#include <string.h>
#include <stdio.h>
char *splitString(char str[], int index, const char delimiter[])
{
char* save_ptr;
int counter = 0;
char *token = strtok_r(str, delimiter, &save_ptr);
while (token != NULL)
{
if (counter == index)
{
return token;
}
token = strtok_r(NULL, delimiter, &save_ptr);
counter++;
}
return NULL;
}
int main(void)
{
char data[] = "#M=1: T=259:S=30:P=5:A=45:D=78:C=0x1";
char *sub1 = splitString(data, 1, ":=");
printf("%s\n",sub1);
char *sub2 = splitString(data, 3, ":=");
printf("%s\n",sub2);
return 0;
}
output:
1
(null)
somebody can say me where i am wrong?
aster94
September 23, 2019, 6:21am
3
Hi,
I have an incoming char array like this:
#M=1:T=259:S=30:P=5:A=45:D=78:C=0x1
And I have to take out the numbers from it. I am willing not to use the String class.
Yes, strtok destroys the string it is working on
Wait, both strtok and strtok_r destroy the string? I thought that strtok_r didn't do that!
If you want to have the original untouched, then make a copy and use strtok on the copy.
Can you say me how? I am going mad with all these pointers, yesterday I wrote that function in 3 hours....
aster94
September 23, 2019, 6:34am
4
I made the copy with strncpy and it works, thanks, do you know how to do it without strncpy? I wish to do it only with pointers!
#include <string.h>
#include <stdio.h>
char *splitString(char str[], int index, const char delimiter[])
{
char str_copy[80];
strncpy(str_copy, str, 80);
char* save_ptr;
int counter = 0;
char *token = strtok_r(str_copy, delimiter, &save_ptr);
while (token != NULL)
{
if (counter == index)
{
return token;
}
token = strtok_r(NULL, delimiter, &save_ptr);
counter++;
}
return NULL;
}
int main(void)
{
char data[] = "#M=1: T=259:S=30:P=5:A=45:D=78:C=0x1";
char *sub1 = splitString(data, 1, ":=");
printf("%s\n",sub1);
char *sub2 = splitString(data, 3, ":=");
printf("%s\n",sub2);
return 0;
}
You can use strchr() to find the delimiter.
Once found
1)
replace delimiter with '\0'
2)
get that field
3)
replace the new '\0' with the delimiter
4)
increment the pointer so it points to after the delimiter
5)
copy the pointer to another variable, that will be the start of the next field
6)
find the next delimiter
7)
back to (1)
Repeat till strchr() returns NULL.