how to split and save [duplicate] - c

This question already has answers here:
Split string with delimiters in C
(25 answers)
Closed 8 years ago.
my problem is next:
char str[25] = "exsample=string=to=split";
char a[2] = "=";
char* token;
token = strtok(str, a);
as you know that code saves first part "exsample" to string token
but how I can take next part of line? meaning string and all after it to split

Just call token = strtok( NULL, a );
But you should consider using thread safe strtok_r() instead of strtok(). The man page for both functions includes a good example.

From the documentation for strtok:
str...
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
In other words:
nextToken = strtok(NULL, a);

Related

How does C programs know the size of a string given a pointer to char? [duplicate]

This question already has answers here:
Does printf terminate every string with null character?
(3 answers)
What's the rationale for null terminated strings?
(20 answers)
Closed 24 days ago.
I would like to understand why this code works:
void open_image(const char *filename)
{
char *ImageName = filename;
printf("%s", ImageName);
}
const char image_name[] = "image.jpg";
open_image(image_name);
it prints "image.jpg" as wanted, but I don't know how the program knows the length of the string.
The program knows the size of the string image_name as it is computed during compilation.
But in the open_image function, how does the printf function knows the length of this string as it is only given the pointer ImageName created at runtime?
Thank you.
In C a string (array of char) is always terminated by the "terminator" character '\0', so you can get the length of the array by checking each character until you find it.
Here's a simple solution:
int i = 0;
char ch;
do
{
ch = arr[i];
i++;
} while(ch != '\0');
printf("String length: %d\n", i-1); // This will give the string length
printf("Total length of the array: %d\n", i); // This will give the array full length, including the terminator character.
Probably the best way to get a char array length is to import the string.h library which exposes the strlen() function.
However, it's always useful to learn how things actually work at low-level, especially when learning C). :-)

String to array elements in C [duplicate]

This question already has answers here:
Split string with delimiters in C
(25 answers)
Why no split function in C? [closed]
(1 answer)
Closed 3 months ago.
I need a function that works in C like split(' ') in python. I have to add words from a string as array elements (so I have to "cut" the string at every space characters and put the words in an array). I have no idea how to do it simply.
I tried for example the strstr() but it's just find the first space in the sentence, but I have 3 spaces.
strtok
"String tokenize"
int main ()
{
char str[] ="one two three";
char * word;
word = strtok (str," ");
while (word != NULL)
{
printf ("%s\n",word);
word = strtok (NULL, " ");
}
return 0;
}
Be careful though, it modifies the input string. It replaces any "delimiter" chars with \0s.
It's also non-reentrant. It keeps state in some global variable so you can't interweave tokenizations of 2 different strings, not even talking about multi-threading.

How can I write words in a string reverse?

I am having a struggle with the following exercise in my book:
Write a program that prompts the user to enter a series of words separated by single spaces, then prints the words in reverse order. Read the input as a string, and then use strtok to break it into words.
Input:hi there you are cool
Output: None it shuts itself.
Expected:cool are you there hi
My program only gets the string and waits and shuts after a couple of seconds. Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int ch ;
char * str , * str2;
char * p;
str = (char*)malloc(sizeof(char) * 100);
str2 =(char*)malloc(sizeof(char) * 100);
if((fgets(str , sizeof(str) , stdin)) != NULL){
str = strtok(str ," \t");
p = strrchr(str , '\0');
strcat(str2,p);
printf("%s",p);
while(str != NULL){
str = strtok(NULL ," \t");
p = strrchr(str + 1, '\0');
strcat(str2,p);
printf("%s",p);
}
}
return 0;
}
I know this question has been asked here. I get the idea there but my problem is implementation and carrying out. This is more of a beginner question.
Since you yourself stated that this is for an exercise I will not provide a working solution but an outline of what you might want to do.
Functions you want to use:
getline - for an easy read of an input line (notice that the newline character will not be eliminated
strtok_r to get the tokens (i.e. the words) from the input string
the _r means that this function is re-entrant which means that it can saftly be called by multiple threads at the same time. The normal version has an internal state and strtok_r lets you manage that state via a parameter.
(Please also read the docs for these functions if you have further questions)
For the algorithm:
Use getline to read a single line from input and replace the newline character with the 0 char. Then you should extract all one token after the other from the input and store them in a stack like fashion. After you tokenized the input just pop the token from the stack an print them to the stdout.
Another approach would be:
Write a function that simply reverses a string. Then use this function to reverse the input string and then for all tokens to read the token from the reversed input string and print the reverse token to stdout.

How to return NULL strings with strtok in C? [duplicate]

This question already has answers here:
Need to know when no data appears between two token separators using strtok()
(6 answers)
Closed 8 years ago.
I'm reading in a .csv file (delimited by commas) so I can analyze the data. Many of the fields are null, meaning a line might look like:
456,Delaware,14450,,,John,Smith
(where we don't have a phone number or email address for John Smith so these fields are null).
But when I try to separate these lines into tokens (so I can put them in a matrix to analyze the data), strtok doesn't return NULL or an empty string, instead it skips these fields and I wind up with mismatched columns.
In other words, where my desired result is:
a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=NULL (or "", either is fine with me)
a[4]=NULL (or "")
a[5]=John
a[6]=Smith
Instead, the result I get is:
a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=John
a[4]=Smith
Which is wrong. Any suggestions about how I can get the results I need will be greatly welcomed. Here is my code:
FILE* stream = fopen("filename.csv", "r");
i=0;
char* tmp;
char* field;
char line[1024];
while (fgets(line, 1024, stream))
{
j=0;
tmp = strdup(line);
field= strtok(tmp, ",");
while(field != NULL)
{
a[i][j] =field;
field = strtok(NULL, ",");
j++;
}
i++;
}
fclose(stream);
Quote from ISO/IEC 9899:TC3 7.21.5.8 The strtok function
3 The first call in the sequence searches the string pointed to by s1 for the first character
that is not contained in the current separator string pointed to by s2. If no such character
is found, then there are no tokens in the string pointed to by s1 and the strtok function
returns a null pointer. If such a character is found, it is the start of the first token.
And the relevant quote for you:
4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the
end of the string pointed to by s1, and subsequent searches for a token will return a null
pointer. If such a character is found, it is overwritten by a null character, which
terminates the current token. The strtok function saves a pointer to the following
character, from which the next search for a token will start.
So you cant catch multiple delimiter with strtok, as it isn't made for this.
It just will skip them.

Concatenating strings (2) [duplicate]

This question already has answers here:
How do I concatenate two strings in C?
(12 answers)
Closed 8 years ago.
char *val1 = "/root";
char *val2 = "/p";
val1 = val1+val2;
I want to add 2 char pointer value and assign it to 1st value. above is the code snippt.
It can't be done that way. Since you have two pointers, trying to add them will try to add the pointers themselves, not manipulate what they point at. To concatenate the two strings, you need to have/allocate a single buffer large enough to hold both:
char *both = malloc(strlen(val1) + strlen(val2) + 1);
if (both != NULL) {
strcpy(both, val1);
strcat(both, val2);
}
Use strcat or strncat functions to concatenate strings. C has no string concatenation operator.

Resources