Reputation: 6404
My Source Code
for(i=0;str[i]!='\0';i++)
{
if(str[i]!=' '){
str2[j]=str[i];
flag=1;
}
if(flag==1 && str2[j]!=' ')
{
printf("\n");
printf("%c",str2[j]);
flag=0;
}
}
My Output:
I am joe
I
a
m
j
o
e
But I want output like this:
I
am
joe
I want each of the word prints in new line like I
in one line am
in another line and joe
in another line also need to remove extra space before joe
Upvotes: 0
Views: 4564
Reputation: 4536
You can follow the Gabriele Method , but if you do not want to put new line character instead of space, you could well do this .
Here we are having only one loop and wherever we see space we are printing newline else printing the character of string and loop continues till i
reaches the value when str[i]='\0'
, then the loop stops.
#include <stdio.h>
int main() {
int i = 0;
char str[] = "I am joe";
while (str[i] != '\0') {
if (str[i] == ' ')
printf("\n");
else
printf("%c", str[i]);
i++;
}
}
Upvotes: 1
Reputation: 681
For example,when you program parse the 'a' of your input"I am joe",the first if statement make str2[j] is 'a' and flag is 1,so the next if condition of course be true,then the printf do the job,print newline and the 'a';
char str[100] = "I am joe";
char str2[100] = {0};
int i,j;
/*flag means alread replace space to newline,so ignore continuous space*/
int flag = 0;
for(i=0, j=0;str[i]!='\0';i++)
{
if(str[i] ==' '){
if(flag != 1){
str2[j++] = '\n';
flag = 1;
}
}
else{
str2[j++] = str[i];
if(flag == 1){
flag = 0;
}
}
}
printf("%s\n", str2);
return 0;
You should learn how to use a debug tools like GDB.
Upvotes: 1
Reputation: 1017
I found it easier to just replace the space characters by new lines
#include <stdio.h>
int main() {
char str[] = "I am joe";
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] == ' ')
str[i] = '\n';
}
printf("%s\n", str);
return 0;
}
All you have to figure out is how to trim those extra spaces....
Upvotes: 2