How do I replace a space with a newline ("\n") in a string using C?
Asked
Active
Viewed 6,768 times
2
-
Your question is not precise enough: in which context do you want to replace a space with a newline? Are you reading a file? scanning a string? – chqrlie Jan 29 '17 at 10:52
-
... also what *exactly* do you consider to be a "*newline*"? – alk Jan 29 '17 at 10:55
-
@chqrlie Better? I created this question because I read a similar question however it did not have any simple straight forward answer and also in his question his code was messy and had variables that were not needed. – Tim Jonas Jan 29 '17 at 11:13
3 Answers
4
#include <stdio.h>
#include <string.h>
#define SIZE 50
int main(int argc, char **argv)
{
char string[] = "this is my string";
size_t length, c;
length = strlen(string);
for(c = 0; c < length; ++c)
{
if(string[c] == ' ')
{
string[c] = '\n';
}
}
printf("%s\n", string);
return 0;
}

Tim Jonas
- 228
- 2
- 16
-
-
1End of string could contain a space but then you would end up with a double new line in most circumstances so ill change it. Cheers for the tip – Tim Jonas Jan 29 '17 at 10:15
-
`strlen()` returns `size_t` not `int`. So `c` and `length` should really be `size_t`. – alk Jan 29 '17 at 10:48
-
1`sprintf(string, "%s", "this is my string");` is no safer than `strcpy(string, "this is my string");`. You should just write `char string[] = "this is my string";` – chqrlie Jan 29 '17 at 10:49
-
-
Because Windows (mostly?) expects `"\r\n"` as new-line, not just `'\n'`. @chqrlie – alk Jan 29 '17 at 10:53
-
@alk: yes, we know about this obsolete convention stolen from CP/M, but `\r\n` sequences are converted to `\n` and vice versa by the standard library when reading and writing text files. Most C program do not need to handle them explicitly. Of course we have no information about the OP's context, so this might indeed be a problem for him. – chqrlie Jan 29 '17 at 10:58
-
@chqrlie: Well yes, fair enough, my thoughts do not hold for the code shown in this answer. Still leaving the comments for clarity. – alk Jan 29 '17 at 11:00
-
Cheers for the comments they are helpful, updated answer still learning c. – Tim Jonas Jan 30 '17 at 10:08
3
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
}
}

chqrlie
- 131,814
- 10
- 121
- 189
-
-
What about some additional error checking/logging like `if ((c == EOF) && ferror(stdin)) {perror("getchar() failed");}` just after the `while`-loop ... :-) – alk Jan 29 '17 at 11:25
-
@alk: `getchar()` indeed returns `EOF` for both end of file and read error. Most unix sample programs blissfully ignore the error case. If one wants to deal with those, your suggestion is fine, but should be completed with equivalent tests on `putchar()` and a check on a final `fflush(stdout)`, leading to cumbersome code with poor pedagogical value. Better error handling would call for a different approach with explicit buffering. – chqrlie Jan 29 '17 at 11:44
1
Simple program:
int c;//return of fgetc type is int
while(EOF!=(c=fgetc(file)))
putchar(c == ' ' ? '\n ' : c);

msc
- 33,420
- 29
- 119
- 214
-
The OP asks *How do I replace a space with a new line in c*, not *How do I replace all spaces with new lines* – chqrlie Jan 29 '17 at 10:50
-
-
1Thats obviously your assumption... but I think you should write `while((c = fgetc(file)) != EOF) putchar(c == ' ' ? '\n' : c);` – chqrlie Jan 29 '17 at 10:55
-