How can I split up a string into pieces? For example, how can I place “orld.” into a variable called one, “Hello” into a variable called three, and ” w” into two?
#include <string.h>
#include <stdio.h>
int main(void)
{
char *text ="Hello World."; /*12 C*/
char one[5];
char two[5];
char three[2];
return 1;
}
For one, you cannot do what you asked, and still have them work as null-terminated strings. This is because the memory layout of
textlooks like this:Notice the
'\0'at the end. The character arraytestis not actually length 12, it is length 13.Null-termination is required for console output functions, like printf and std::cout (C++) to work:
This means that you must define your arrays like this:
You can do this by hand by simply copying the values out:
If you want to do less typing, or simply want to write better code, you can take advantage of the fact that arrays/strings are contiguous, and use a loop to copy that data over:
But if you guess that this is a really common thing to do in C, then you guess right. Instead of manually coding this loop each time, you should use a built-in function to do the copying for you: