Thread: give a look into my TRIM function (please comment)

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    18

    give a look into my TRIM function (please comment)

    hey guys! this is my first pointers act. just learning about pointers.
    I need you guys say me something about this function.
    Is it good? what should I improve?
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    char *trim_str(char *string);
    
    void main()
    {
    	char s[] = "   	string teste   	   ";
    	printf("--%s--",trim_str(s));
    }
    
    char *trim_str(char *string){ /*remove spaces before*/
    	char *a;
    
    	if (isspace(*string)){
    		while (isspace(*string++));
    		string--;
    		trim_str(string); /*2nd call to remove spaces after*/
    	} else { /*remove spaces after*/
    		a = string + (strlen(string)-1);
    		while (isspace(*a--));
    		a+=2;
    		*a='\0';
    	}
    	return(string);
    }

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> Is it good?
    Code:
    trim_str(s);
    printf("--%s--", s);
    Modify and return the parameter.

    >> what should I improve?
    Don't use recursion.

    gg

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    don't use void main either

    It would be a good idea to provide an additional buffer of where you want the trimmed string stored. Modifying strings "in place" is a bit anti-social (especially in large programs where it may go unnoticed for a while).
    You cannot for example trim
    Code:
    char *s= "   	string teste   	   ";
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Sep 2003
    Posts
    18
    hey thank you guys!
    im a newbie

    Modify and return the parameter.

    Don't use recursion.
    What is wrong with recursion? How should I change it?

    -------------------------------------------------------
    You cannot for example trim
    Code:

    char *s= " string teste ";
    and how would I change it?

    please guys! post your code suggestions!

  5. #5
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The function returns a pointer that may not point to the first element in the array - not a good idea at all! If the array was dynamically allocated that would certainly lead to a memory leaks. Instead, move the desired data to the beginning of the array, and be sure to return a pointer to the first element.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >What is wrong with recursion?
    It doesn't really simplify the problem to use recursion, and you can easily just use two loops to do the same thing.

    >How should I change it?
    Use loops:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    char *trim_str(char *string);
    
    int main()
    {
      char s[] = "   	   ";
      printf("--%s--",trim_str(s));
      return 0;
    }
    
    char *trim_str(char *string){
      char *a;
    
      while ( *string && isspace ( *string ) ) {
        string++;
      }
      a = string + ( strlen ( string ) - 1 );
      while ( a != string && isspace ( *a ) ) {
        a--;
      }
      if ( *a != '\0' )
        a[1] = '\0';
    
      return(string);
    }
    >and how would I change it?
    String literals cannot be portably modified. To fix your code to handle them you will need to either do some dynamic memory allocation, or require the caller to pass a buffer large enough to hold the trimmed string.
    My best code is written with the delete key.

  7. #7
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> Modify and return the parameter.
    That means what Sebastiani said. Or in other words, the pointer address that passed in should be the pointer address that's returned.
    Otherwise, you can change your API so that the caller is responsible for providing the output buffer to store the trimmed result as Salem suggested.

    >> What is wrong with recursion?
    Nothing wrong with it, it's just over kill in this situation.
    You're using recursion for a simple two-step process: trim the beggining then trim the end.

    >> post your code suggestions!
    We are
    You seem more than capable of implementing our suggestions.

    gg

    [EDIT]
    Late posting...

  8. #8
    Registered User
    Join Date
    Sep 2003
    Posts
    18
    i changed it. now the function do not returns a pointer. now it change the string directly on its location:
    Code:
    #include <string.h>
    #include <ctype.h>
    
    void trim_str(char *string);
    
    int main(){
    	char str[] = "     	string test   	";
    	
    	trim_str(str);
    	
    	printf("-%s-", str );
    	
    	return(0);
    }
    
    
    void trim_str(char *string){
    	char *a;
    	a = string;
    	if (isspace(*string)){
    		while (isspace(*a++)); /* set pointer to the first non-space char */
    		a-=2;
    		while (*a++ != '\0'){
    			*string = *a;
    			string++;
    		}
    		string-=(a-string); /*reset pointer to startup pos*/
    	}
    	string+=strlen(string)-1; /* set pointer to the last char */
    	while(isspace(*string--));
    	string+=2;	
    	*string='\0';
    }
    please, comment it!
    Last edited by aze; 04-21-2004 at 12:18 PM.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you want a safe implementation, you should be passing a buffer to copy the info into. Otherwise, again, string literals will do BadThingsTM.
    Code:
    trim_str("  BadThingsTM    " );
    Also, you can simplify this a bit...
    Code:
    void trim( char *O0OO, char *O00O )
    {
            char *O000 = O0OO;
            char *OO0O = O000+strlen(O0OO)-1;
            while( isspace( *O000 ) ) O000++;
            while( isspace( *OO0O ) ) OO0O--;
            while( O000 <= OO0O )
                    *O00O++ = *O000++;
    }
    Something like that, assuming I'm reading your problem right. However, you'll not want to turn that in for homework.

    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    One thing I noticed was some unnecessary math that could be eliminated by using better structured loops. For instance:


    Code:
    while (isspace(*a++)); 
    		a-=2;
    		while (*a++ != '\0'){
    			*string = *a;
    			string++;
    		}

    Could be made more readable using something like:


    Code:
    while (isspace(*a)) a++; 
    		while (*a != '\0'){
    			*string = *a;
    			string++, a++;
    		}

    Otherwise, the function looks good. Here's another version of the function:


    Code:
     char * trim(char * str)
    {
     int length = strlen(str);
    
         if(length > 0)
        {
         char * data = str;
         char * front = str;
         char * back = str[length];
    
         while(isspace(*front))  ++front;
    
         while(isspace(*(back-1)))  --back; 
    
         while(front < back)  *(data++) = *(front++);  
    
         *data = 0;
        } 
    
     return str;
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  3. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  4. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  5. Replies: 4
    Last Post: 11-23-2003, 07:15 AM