User-defined String Functions

These are the functions that I described in class. You should try to see if you can follow the logic without any comments in the code.

int my_strlen(const char string[])
{
  int i = 0;

  while (string[i] != 0)
    i++;
  
  return i;
}



void my_strupr(char string[])
{
  int i = 0;

  while (string[i] != 0)
  {
    string[i] = toupper(string[i]);
    i++;
  }
}



void my_strcpy(char string1[], const char string2[])
{
  int index = 0;

  while (string2[index] != 0)
  {
    string1[index] = string2[index];
    index++;
  }
  string1[index] = 0;
}



void my_strcat(char string1[], const char string2[])
{
  int index1 = 0, index2 = 0;

  while (string1[index1] != 0)
    index1++;

  while (string2[index2] != 0)
  {
    string1[index1] = string2[index2];
    index1++;
    index2++;
  }
  string1[index1] = 0;
}



int my_strcmp(const char string1[], const char string2[])
{
  int index = 0;
  char ch1, ch2;

  ch1 = string1[index];
  ch2 = string2[index];

  while ( (ch1 != 0) && (ch2 != 0) )
  {
    if (ch1 < ch2)
      return -1;
    else if (ch1 > ch2)
      return 1;

    index++;
    ch1 = string1[index];
    ch2 = string2[index];
  }

  if ( (ch1 == 0) && (ch2 == 0) )
    return 0;
  else if (ch1 == 0)
    return -1;
  else
    return 1;
}


Previous page

Back to Lesson 13 Index
Back to Outline