Computer Science 2611
Summer 2000
Laboratory Assignment 9

For this lab, write the following string manipulation functions. Do not use the functions in the string.h library for this assignment. (All of these functions have equivalents in the string library.) Test the functions in any way that you see fit, but test them thoroughly. Do not turn in untested functions! Be sure to test unusual cases, such as empty strings.

Turn in your functions and your test program. The test program should test all of the functions. Don't throw away tests after they work.

Functions strlen and strcpy were written in the lecture. You may feel free to use the lecture versions of those functions.

  1. strlen(s) should return the length of null-terminated string s. For example, strlen("abcd") = 4.

  2. strcpy(s,t) should copy null-terminated string t into array s. After doing strcpy(s,t), array s should hold the same string as array t, and s should be null-terminated. Assume that enough space is available in array s.

  3. strcat(s,t) should copy null-terminated string t to the end of null-terminated string s. For example,
        strcpy(s, "abcd");
        strcat(s, "xyz");
      
    should end with array s holding null-terminated string "abcdxyz". Function strcat should presume that enough room is available in array s.

  4. strcmp(s,t) should compare null-terminated strings s and t according to alphabetical order. strcmp(s,t) should return

    -1 if s comes before t in alphabetical order
    0 if s and t are identical
    1 if s comes after t in alphabetical order

    Think about how to compare strings. You start with the first character of each string. You only continue to the next character if those characters are the same.

    If s is a prefix of t (for example, if s is "abc" and t is "abcde"), then strcmp(s,t) should return -1. Similarly, if t is a prefix of s, then strcmp(s,t) should return 1.

    You should use the standard ascii ordering of characters. You can compare two characters using comparisons such as < and >. Note that this will cause strcmp("DD","aa") to return -1, since character 'D' has a smaller ascii code than character 'a'. That is ok.

  5. strchr(s,c) tells where character c occurs in string s. Make it return the index of the first occurrence of c in string s, or -1 if there is no such character in s. For example, strchr("abcd", 'b') = 1 since 'b' occurs at index 1 in "abcd". (Remember that the first character is at index 0.) Note that strchr("abcd", 'e') = -1 since character 'e' does not occur in string "abcd".

    Note: There is a standard library function called strchr that behaves similarly to this function, but not quite the same. It returns the memory address of the character rather than its index.

    Note: Function strchr should work correctly when character c is the null character. It should return the index where the null character is located (at the end of the string).