1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Need help,im beginner

Discussion in 'C' started by uric, Jun 9, 2012.

  1. uric

    uric New Member

    Joined:
    Jun 9, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello guys
    I want to reverse some text and delete the spaces if the spaces are more than one

    i mean this :
    hello world ---> hello world
    4 spaces ---> 1 space

    Code:
    void reversed(char str[]);
    int main(int argc, char *argv[])
    {
        char str[100];
        printf("enter text : ");
        gets(str);
      reversed(str);
        return 0;
    }
    void reversed(char str[])
    {
         int i;
         for (i = strlen(str) - 1; i>=0; i--)
         printf("%c",str[i]);
         printf("\n");
      system("PAUSE");    
      return 0;
    }
    
    this code was fore reverse

    Code:
    int main()
    {
       char text[100], blank[100];
       int c = 0, d = 0;
      
       printf("Enter some text\n");
       gets(text);
      
       while (text[c] != '\0')
       {
          if (!(text[c] == ' ' && text[c+1] == ' ')) {
            blank[d] = text[c];
            d++;
          }
          c++;
       }
      
       blank[d] = '\0';
      
       printf("Text after removing blanks\n%s\n", blank);
     system("PAUSE");
       return 0;
    }
    
    and thi code was fore deleting spaces

    but i want to reverse and delete spaces at the same time,can anyone give me a solution ?
    i want these two codes in one
    thanks a lot
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Nice job with trying it out. :)

    beware when using gets; that function doesn't check that input will fit within your array and will gladly overflow if allowed to.

    Since you're using a temp array as well, add another argument to your function

    Code:
    void myfunction(char *src, char *des) {
    
       /* reverse a string and remove extra spaces */
    
       int i = strlen(src) - 1, j = 0, spc = 0;
    
       while(i >= 0) {
          if(spc == 0 && src[i] == ' ') // is src[i] a space ??
             spc = 1; // it's a space, so set flag         
          else {
             while(src[i] == ' ') // loop while src[i] is extra spaces
                --i; 
              spc = 0; // reset space flag
          }
    
          des[j] = src[i]; 
          --i;
          ++j;
       }
    
       des[j] = '\0'; // add string termination char
    }
    to test with, from main

    Code:
    char source[] = "string       with        extra      spaces",
         dest[50] = { 0 };
    
    myfunction(source, dest);
    puts(source);
    puts(dest);
    make sure the destination string is big enough and is initialized to get rid of any junk chars.

    hope that helps.
     

Share This Page