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.
Related
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). :-)
This question already has answers here:
char* value changing after use of fgets
(1 answer)
How to return 2d char array (char double pointer) in C?
(1 answer)
Closed 10 months ago.
I am wanting to take in an input from a string, then go through each line and parse the line into sub strings by splitting using spaces. I have a while loop nested in a while loop to try and get this work. When I print the char* in the loop I get the expected output, but once exiting the loop and then printing different position I get unexpected values.
while ((getline(&line, &len, fp)) != -1){
//line is an array of characters
//piece is a char pointer that stores the sub strings of a line
//where a string is broken into sub strings by a space
char *piece = strtok(line, " ");
while(piece != NULL){
tokens[j] = piece;
printf("%s\n", tokens[j]);
piece = strtok(NULL, " ");
j++;
}
}
printf("%s\n", tokens[0]);
You either need to not overwrite line (per #AdrianMole) for instance by realloc(line, new_larger_size) so it can hold your entire input, or copy each token and subsequently free the memory allocated with for example strdup():
tokens[j] = strdup(piece);
...
// cleanup: assumes last tokens[i] is NULL. If tokens itself is heap allocated you need to free it too
for(int i = 0; tokens[i]; i++) free(tokens[j]);
I answered a somewhat similar question yesterday: How to return 2d char array (char double pointer) in C?
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 3 years ago.
I have made this function to extract the first 2 characters of a string:
string get_salt(string hash)
{
char pre_salt[2];
for (int i = 0; i < 2; i++)
{
pre_salt[i] = hash[i];
}
string salt = pre_salt;
printf("%s\n", salt);
return(salt);
}
But when I run it with a string that has "50" (is the example I'm using) as the first 2 characters, I get this output:
50r®B
And to be honest I have no idea why is it adding the 3 extra characters to the resulting string.
You are missing the string's NUL terminator '\0' so it keeps printing until it finds one.
Declare it like:
char pre_salt[3]={0,0,0};
And problem solved.
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);
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.