Strtok to separate all whitespace - c

I'm trying to split a string at spaces and tabs.
char * token = strtok(input, " \t");
works only for spaces. What am I doing wrong?

Here is an example that illustrates that strtok() will work on tabs or spaces.
The key is to pass in NULL on the all but the first call to strtok().
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buffer[1024];
int rv = sprintf(buffer, "a string\ttokenize.");
char *token = strtok(buffer, " \t");
int i = 0;
printf("cnt token\n");
printf("==========\n");
while (token) {
printf("%2d %s\n", i++, token);
token = strtok(NULL, " \t");
}
return 0;
}
output from above program is as follows below.
cnt token
==========
0 a
1 string
2 tokenize.

Related

Segmentation error when convert string to array of strings in c

I want to convert a string to an array of strings and I get an error
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int count = 0;
char *str = argv[1];
char *token, *last;
char **arr_str = calloc(9999, sizeof(char*));
token = strtok_r(str, " ,", &last);
arr_str[count] = strcpy(calloc(strlen(token), sizeof(char)), token);
while (token != NULL) {
count++;
token = strtok_r(NULL, " ", &last);
arr_str[count] = strcpy(calloc(strlen(token), sizeof(char)), token);
printf("%s", arr_str[count - 1]);
}
printf("------------");
while(arr_str[count])
printf("%s", arr_str[count--]);
exit (0);
}
how to allocate memory for a string and make a pointer to it from an array?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
/* always check argument count */
if(argc < 2) {
printf("Not enough arguments given\n");
return 1;
}
int count = 0;
char *str = malloc(strlen(argv[1] + 5));
memcpy(str, argv[1], strlen(argv[1]));
char *token, *last;
char **arr_str = calloc(9999, sizeof(char*));
token = strtok_r(str, " ,", &last);
while ((token = strtok_r(NULL, " ", &last)) != NULL) {
count++;
/* sizeof(char) is always 1 and is redundant unless you are on
a obscure platform that it returns other than 1
which shouldnt exist in modern world
*/
arr_str[count] = malloc(strlen(token) + 1);
strcpy(arr_str[count], token);
}
printf("------------");
while(arr_str[count])
printf("%s", arr_str[count--]);
exit (0);
}
strtok is destructive meaning it edits strings it encounters, it tried to edit argv which resulted in a segmentation error.
I also edited code to follow better practices and edited formatting.
You need memory for elements of the arr_str.
calloc(9999) while not great if this not going to end up in a serious application it's not a issue.
sizeof(char) should always return 1 on a normal modern system unless you are on extremely obscure system
Use puts(char* s) if you don't need string formatting.
You should do input validation.

How can I add a string to an array of strings in C?

I have a string "token" and an empty array of strings "arr". I want to add token to the first index of arr. I've tried arr[0][0] = token, but this would only work for chars and I've also tried arr[0] = token but this throws the error "expression must be a modifiable lvalue". My full program is:
#include <stdio.h>
#include <string.h>
char arr[100][100] = {};
char *token = strtok(StringToBeSplit, " ");
int i = 0;
while(token != NULL) {
arr[0] = token;
printf("%s\n", token);
token = strtok(NULL, " ");
i++;
}
What should I do?
You need to avoid assigning string literal to strtok. Basically using strcpy to copy the token to array and increment array as advised by previous answer. Something like this:-
#include <stdio.h>
#include <string.h>
int main(){
char arr[100][100] = {};
char str[] = "Split this string";
char sep[] = " ";
char *token = strtok(str, sep);
int i = 0;
while(token != NULL){
strcpy(arr[i], token);
token = strtok(NULL, sep);
i++;
}
//Test If it can print the strings
for(int j = 0; j < i; j++)
printf("%s\n", arr[j]);
}

Split string and append them to an array

Let's say I have a string containing integers "1 3 4 9" and I want to separate them based on the whitespace between them, and then save them into an array.
For example:
Input:
char str[] = "1 3 4 9";
int arr[4];
Then arr should be like:
arr[] = {1, 3, 4, 9}
How to do that in C, please help me. Hope I made the question clear
You can use strtok:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "1 3 4 9";
char *token = strtok(str, " ");
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
Your desired functionality in C.
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "1 3 4 9";
char newstr[50];
char *token = strtok(str, " ");
while (token != NULL)
{
printf("%s\n", token);
strcat(newstr, token);
token = strtok(NULL, " ");
}
printf("Newstr: %s",newstr);
return 0;
}
It will work with any string which will be including white space in it.

Using place holders as delimiters

I have been trying to make it so that placeholders like (%c) or (%d) are used as delimiters but whenever I try to it will also use the letter after the percent as a delimiter as well. Is there a way to make it so that both characters together are the delimiter and not so they are separate delimiters.
#include <stdio.h>
#include <string.h>
int main (void){
char string[100];
printf("Enter a string: ");
fgets(string,sizeof(string),stdin);
string[strlen(string)-1] = '\0';
char seperator[] = " %c";
char *token = strtok(string,seperator);
while(token != NULL){
printf("%s\n",token);
token = strtok(NULL,seperator);
}
return 0;
}

break a string into 'first' and 'second'

I have read through countless strtok posts, even copied some directly in their entirety into a new int main, but I can't figure out how to create the functions get_first and get_second.
get_first("This is a sentence."); //returns "This"
get_rest("This is a sentence."); //returns "is"
This is what I have so far, I have had nothing but trouble with strtok, but I don't know what else to use.
#include <stdio.h>
#include <string.h>
char * get_first(char * string) {
string = strtok(string, " ");
return string;
}
char * get_second(char * string) {
string = strtok(string, " ");
string = strtok(NULL, " ");
return string;
}
int main(int argc, char * argv[]) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
}
Getting no faults compiling with gcc -g -Wall, but it always seg faults. I think I have tried every permutation of char c[] and char * c there is.
strtok changes the string. (but String literals are not allowed to change.)
So create a copy.
Do the following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * get_first(const char *string){
char *clone = strdup(string);//create copy, strdup is non standard. malloc and copy.
char *token = strtok(clone, " ");
if(token)
token = strdup(token);
free(clone);
return token;
}
char * get_second(const char *string) {
char *clone = strdup(string);
char *token = strtok(clone, " ");
if(token && (token = strtok(NULL, " ")))
token = strdup(token);
free(clone);
return token;
}
int main(void) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
free(first);
free(second);
}

Resources