简体   繁体   中英

print each word in new line with removing extra space in c programming

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

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....

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.

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++;

  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM