Reliable Software Logo

C++ In Action

Exercise Solutions

  1. Here's one possibility:
    void StrCpy (char * strDest, char const * strSrc)
    {
        int i = 0;
        char c;
        do
        {
            c = strSrc [i];
            strDest [i] = c;
            ++i;
        } while (c != '\0');
    }
  2. Notice how the same condition takes care of a character difference and str2 being shorter. In general, such optimizations are not recommended, because they obscure the code.
    int StrCmp (char const * str1, char const * str2)
    {
        int i = 0;
        while (str1 [i] != '\0')
        {
             int diff = str1 [i] - str2 [i];
             // this also takes care of end of str2
             if (diff != 0)
                 return diff;
             ++i;
        }
        if (str2 [i] == '\0')
            return 0;
        // str1 is shorter
        return -1;
    }
  3. Here's one way to do it. However, the specification wasn't complete. It didn't say what to do the case when the source string's length is greater than or equal to len. Should the destination string then be terminate by a null character at the offset len - 1? What do you think?
    void StrNCpy (char * strDest, char const * strSrc,
                                    std::size_t len)
    {
        for (std::size_t i = 0; i < len; ++i)
        {
            strDest [i] = strSrc [i];
            // early exit
            if (strSrc [i] == '\0')
                break;
        }
    }