C-Style String Homework Answers

1. int main()
   {
      char line[81];
      cout << "Enter a string\n";
      cin.getline(line,81);
      int i = 0;
      while (line[i] != '\0')
      {
         while (line[i] != ' ' && line[i] != '\t'
                              && line[i] != '\0')
         {
            cout << line[i];
            i++;
         }
         cout << endl;
         while (line[i] == ' ' || line[i] == '\t')
            i++;
      }
   }


2. void revstr(char forward[], char backward[])
   {
      int i, j;
      i = lengthstring(forward) – 1;
      for (j = 0 ; i >= 0 ; j++, i--)
         backward[j] = forward[i];
      backward[j] = '\0';
   }


3. 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;
   }


4. 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;
   }


5. 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];
   }


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

© Copyright Emmi Schatz 2003