Thread: C++ Implementing String Operations

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    46

    C++ Implementing String Operations

    hey guys, I was wondering if you can look over some code:

    1. char* reverse(char *s);

    *Here, s is a C-string. Its return value should be a newly-allocated C-string, said string being the reversal of the
    string s. Hence, the return value of reverse("abcde") would be "edcba". *

    Code:
    {
       char *t;
       int i, n;
       n=length(s);
       t = new char[n];
       for (i=0; i<n; ++i)
       {
           *(t+i)=*(s+n-1-i);
       }
       *(t+i)='\0';
       
       return t;
    }
    }
    2. char* trimfront(char *s);

    *Here, s is a C-string. Its return value should be a newly-allocated C-string, consisting of s, but with all initial whitespace characters removed*

    Code:
    {
    while(*s == ' ' || *s == '\t')
    	s++;
    	return s;
    }
    3. char* trimrear(char *s);

    *Here, s is a C-string. Its return value should be a newly-allocated C-string, consisting of s, but with all final whitespace characters removed*

    Code:
    char* trimrear(char *s) (
    {
        char *s;
        s=str; 
        while(*s){  (
    	    if(isspace(*s))  
    		s++; 
    	    else 
    		break; 
    	    )
    	    return s; 
    }
    4. char* vowels(char *s);

    *Here, s is a C-string. Its return value should be a newly-allocated C-string consisting of all the vowels found in s, in the order found, taking case into account.*

    (somebody was helping with this for me, but there seems to be a problem with the strcat)
    Code:
    {
    char* out = "";
    for (i=0;i<strlen(s);i++)
    {
    char a = s[i];
    switch (a)
    {
    case 'A':
    case 'a':
    case 'E':
    case 'e':
    // similarly i,o,u
    strcat(out,a);
    default: ;
    } // end switch
    } // end for
    return out;
    }
    Note: I am aware that there will be segmentation faults unless I include the new operator.

    Thanks to everybody who helps..

  2. #2
    Registered User Swarvy's Avatar
    Join Date
    Apr 2008
    Location
    United Kingdom
    Posts
    195
    For the first one, you ever thought of doing something like:

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    char function(string str, unsigned int position);
    
    char function(string str, unsigned int position)
    {
         string::reverse_iterator reverse;
         reverse = str.rbegin() + position;
         return (*reverse);
    }
    
    int main(int argc, char *argv[])
    {
        string str = "Testing String... TO BE REPLACED...";
        int idx=0;
        
        for(idx=0; idx<str.length(); idx++)
        {
                   cout << function(str, idx);
        }
        
        cout << "\n";
        return EXIT_SUCCESS;
    }

  3. #3
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    First, all of your functions seem to have the requirement of "return a newly-allocated string" - so, since they're not modifying their input, they should probably be function(const char *input);

    Let's take one:
    Code:
    {
    while(*s == ' ' || *s == '\t')
    	s++;
    	return s;
    }
    This doesn't seem to allocate a new string.

    Code:
    {
       char* out = "";
       for (i=0;i<strlen(s);i++)
       {
          char a = s[i];
          switch (a)
          {
          case 'A':
          case 'a':
          case 'E':
          case 'e':
          // similarly i,o,u
             strcat(out,a);
          default: ;
          } // end switch
       } // end for
       return out;
    }
    This one is a mess. You need to allocate a string - you cannot just say char *out = "". char *out = "" set's char pointing to an empty string, in possibly read only memory! (It should really be const char *out = "", but that does us no good since we want to modify out.) Allocate memory for the string.
    Once you get it functional, then:
    Make your call to strlen() outside the loop - otherwise, you may be taking a string length each time you loop - which is not needed.
    Keep track of the end of the string yourself, and you can avoid the strcat() inside the loop. (Again, calling strcat each time will make the running time of the function O(n^2). This function should be O(n) when you're done.)
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    {
       char *t;
       int i, n;
       n=length(s);
       t = new char[n];
       for (i=0; i<n; ++i)
       {
           *(t+i)=*(s+n-1-i);
       }
       *(t+i)='\0';
       
       return t;
    }
    Your allocated array has length n which means a valid index from 0 through n-1. In your loop, i goes from 0 and stops once it reaches n. You then attempt to use this value in i (which is n) to index the allocated array which is one past the allowable bounds (n-1). Short answer is you need to allocate an extra byte for the array to store the null.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Depending on how much i is. In any case strlen doesn't count the null terminator, but the new string must have it, so you need one character more.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by jewelz View Post
    ok so to allocate memory for the vowels function, should it be

    Code:
    temp = new char[i]
    and how do i use the strlen? temp = strlen(s)?
    Unless the original string is ginormous, what's the problem with allocating the worst case - the input string consists of only vowels. Generally, the C library will round up to 16 or 32 bytes anyways.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    s, t, r, i, n, g, \0

    That's a string of 6 characters (as returned by strlen) requiring 7 char's worth of memory.

    Naturally you can count the vowels first and then allocate that much + one char for the null terminator, but there is nothing wrong if you use more memory for the string. E.g memory for the vowels in "string" might look like this:

    7 bytes:
    i, \0, z, w, q, z, x

    Who cares what garbage comes after the null terminator since you are not going to look at that.
    Last edited by anon; 05-05-2009 at 04:06 PM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. standard String operations
    By kolucoms6 in forum C++ Programming
    Replies: 3
    Last Post: 03-09-2008, 12:47 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM