Home > Articles, Data Structures & Algorithms > Implementation of basic string processing functions in C.

Implementation of basic string processing functions in C.

Below there are some basic processing functions of strings in C. The implementations are approached with the pointers of C, thus creating faster and more compact code.

You should know that the implementation of the algorithms does not take into account issues of data input validation or proper management of dynamic memory (e.g. avoiding memory leaks) because it is only necessary to highlight the logic of the algorithms.

Calculating string length:

size_t
strlen (const char * s) {
  const char * z = s;
  while (*z++) ;
  return z-s-1;
}

Copy a string:

char *
strcpy (char * s1, const char * s2) {
  char * z = s1;
  while (*s1++ = *s2++) ;
  return z;
}

Compare strings:

int
strcmp (const char * s1, const char * s2) {
  while (*s1++ == *s2++)
  if (*(s1-1) == 0)
    return 0;

  return *(s1-1) - *(s2-1);
}

Compare strings (prefix):

int
strncmp (const char * s1, const char * s2, size_t n) {
  int i = 0;

  while (i < n && *s1 != 0) {
    if (*s1 != *s2)
      return *s1 - *s2;

    i++, s1++, s2++;
  }

  return 0;
}

Append string:

char *
strcat (char * s1, const char * s2) {
  return strcpy (s1 + strlen (s1), s2);
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: