Reputation: 228
How do I replace a space with a newline ("\n") in a string using C?
Upvotes: 2
Views: 7912
Reputation: 228
#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;
}
Upvotes: 4
Reputation: 34608
Simple program:
int c;//return of fgetc type is int
while(EOF!=(c=fgetc(file)))
putchar(c == ' ' ? '\n ' : c);
Upvotes: 1
Reputation: 144780
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
}
}
Upvotes: 3