How do I replace a space with a newline ("\n") in a string using C?
Your question is quite vague.
Here is a simplistic filter to change all spaces in the input stream into newlines:
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
putchar(c == ' ' ? '\n' : c);
}
return 0;
}
EDIT:
If you are interested in modifying a string, you should be aware that string literals are not modifiable, attempting to modify them has undefined behavior.
You should locate the space characters and store newline characters ('\n'
) at the corresponding offsets.
You can use a pointer and the strchr()
function:
char *p = strchr(string, ' ');
if (p != NULL) {
*p = '\n';
}
Handling all spaces in a loop:
for (char *p = string; (p = strchr(p, ' ')) != NULL; p++) {
*p = '\n';
}
Or you can use a for
loop with an index variable:
for (size_t i = 0; string[i] != '\0'; i++) {
if (string[i] == ' ') {
string[i] = '\n';
//break; // uncomment the break if you want a single space changed
}
}