I am new to the programming world and I'm trying to make a string split by using a loop that should split all characters separately but it's being ignored and basically ends with showing the input of the user instead of using the loop to separate the individual letters/characters. Have I missed declaring something important in the loop?
3 Answers
for (i = 0; str[i] != '\0'; i++);
<- there's a semicolon here, so your loop literally does nothing
also note that str[i] != '\0'
is a very dangerous way of iterating your string. If your string doesn't contain a zero-terminal character, C will happily continue reading memory beyond the end.
-
strlen(str)
will loop overstr
until it finds a null terminator. So there's really no difference between that and doing it manually. Unless you havei < strlen(str)
as the loop condition in which case you've just made your loopO(n*n)
instead ofO(n)
– KevinCommented Dec 16, 2018 at 21:34 -
I guess you're correct on that one. You could always go with
sizeof(str)
, but that will include\0
. Long story short, C and strings are still not friends.– nitowaCommented Dec 16, 2018 at 21:39 -
It depends on what you want.
sizeof(str)
returns the number of bytes thatstr
takes up, which in this case is 50.strlen(str)
is the length of the C-style stringstr
. Sincefgets
was usedstr
will be a C-style string, i.e. it will have a null terminator. Just callstrlen(str)
once outside of the loop to be more efficient.– KevinCommented Dec 16, 2018 at 21:42
There are few syntactical errors with what you posted.
/* This should be <stdio.h>
...
/* Don't need a. semi-colon here
int main();
...
/* Calling getchar() will cause you to lose the first character of the
the input
*/
getchar();
...
/* Don't need a semi-colon here */
for (i = 0; str[i] != '\0'; i++
...
system("pause");
}
With those adjustments you should find the code works.
Write text:
Hello world
Input: Hello world
H
e
l
l
o
w
o
r
l
d
sh: pause: command not found
I'm not on windows, so if the code on your end does not seem to work after making adjustments it is probably windows specific.
If you're using java, you can just split with an empty string and then loop through the list that's created from the split method.