So I am fooling around with strchr
to get part of a string from a file:
void manipulateComputers(char *name)
{
name[strlen(name)-2] = '\0';
printf("%s\n", name);
char *ptr = strchr(name, ' ');
printf("%s\n", ptr);
}
At the first printf
it reads:
zelda 1 flux 1 hydra 1 willow 1 swift 1 aeon 1 neptune 1
At the second printf
it reads:
1 flux 1 hydra 1 willow 1 swift 1 aeon 1 neptune 1
As you can see, the zelda
is gone, which is kind of what I wanted to do. I wanted to remove the zelda
, but now I want to use zelda
.
Essentially, I wanted the second printf
to print just zelda
and not the string without zelda
.
How do I get a hold of that zelda
to eventually pass it to another function. Thanks
You've not lost zelda
; the pointer name
still points to it.
You can print zelda
using (amongst other techniques):
int z_len = ptr - name;
printf("Zelda was here: %*.*s\n", z_len, z_len, name);
The advantage of this technique over many alternatives is that the original string is still intact — unmodified. This means it also works when the string is a const
string, such as a string literal.