C-Style String Worksheet Two Answers


1. int Equal(char first[], char second[])
   {
      int result = 1;
      int firstlen = lengthstring(first);
      int seclen = lengthstring(second);
      if (firstlen != seclen)
         result = 0;
      else
         for (int i = 0 ; i < firstlen && result == 1 ; i++)
            if (first[i] != second[i])
               result = 0;
      return result;
   }


2. int indexOf(char str[], char ch)
   {
      int result = -1;
      int length = lengthstring(str);
      for (int i = 0 ; i < length && result == -1 ; i++)
         if (str[i] == ch)
            result = i;
      return result;
   }


3. void trimfront(char str[])
   {
      for (int non = 0 ; non < lengthstring(str) &&
                              str[non] == ' ' ; non++);
      if (non != 0)
         for (int i = 0 ; i < lengthstring(str) – non + 1 ; i++)
            str[i] = str[i+non];
   }


4. line is: this is a test; IT IS ONLY A TEST
   length of first: 4
   first is: this
   line is: this is a test; IT IS ONLY A TESTthis
   third is: THIS IS A TEST
   sec is: this is a test


5. #include <iostream.h>
   #include <string.h>
   void concat(char str1[],char str2[],int maxlen)
   {
      int lenstr1 = strlen(str1);
      int lenstr2 = strlen(str2);
      if ((lenstr1 + lenstr2) < maxlen)
         strcat(str1,str2);
      else
         strncat(str1,str2,(maxlen-(lenstr1+1)));
   }



Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002