C-Style Strings

There are two ways to keep track of the the number of items in an array:

  1. keep a count of how many items are in the array
  2. use a marker after the last valid item in the array

A C-style string is a null (denoted by \0) terminated char array. The null occurs after the last character of the string. For an initialization using double quotes, "...", the compiler will insert the null. Except for str2 having more room, the following are all equivalent.

char str1[]  = "hi!";                  // compiler can determine array size 
char str2[20]= "hi!";                  // plenty of room
char str3[4] = "hi!";                  // min size, must allow room for null
char *str4   = "hi!";                  // pointer equivalent
char str5[]  = {'h', 'i', '!', '\0'};  // the above are equivalent to this

C-style strings are often dealt with as char pointers.

There are many functions to work on C-style strings including (check the manual entries);

#include <string.h>

char *  strcat ( char * dest, const char * src );

Append string.
  Appends src string to dest string. The terminating null character in dest is overwritten by the first character of src. The resulting string includes a null-character at end.

Parameters.

dest
Pointer to a null-terminated string with enough space allocated to contain both src and dest.
src
Null-terminated string to append.

Return Value.
  dest is returned.

Portability.
  Defined in ANSI-C.

Example.

/* strcat example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[80];
  strcpy (str,"strings  ");
  strcat (str,"have been ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}
Output:
strings have been concatenated.

back to top


char *  strchr ( const char * string, int c );

Find character in string.
  Returns the first occurrence of c in string.
  The null-terminating character is included as part of the string and can also be searched.

Parameters.

string
Null-terminated string scanned in the search.
c
Character to be found.

Return Value.
  If character is found, a pointer to the first occurrence of c in string is returned.
  If not, NULL is returned.

Portability.
  Defined in ANSI-C.
  ANSI-C++ standard specifies two different declarations for this function instead of the one included in ANSI-C:

const char * strchr ( const char * string, int c );
      char * strchr (       char * string, int c );
  Both have the same behavior as the original declaration.

Example.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}
Output:
Looking for 's' character in "This is a sample string"...
found at 4
found at 7
found at 11
found at 18

back to top


int  strcmp ( const char * string1, const char * string2 );

Compare two strings.
  Compares string1 to string2 character by character.
  This function starts comparing the first character of each string. If they are equal to each other continues with the following pair until the characters differ or until end of string is reached.

Parameters.

string1
Null-terminated string to compare.
string2
Null-terminated string to compare.

Return Value.
  Returns a value indicating the lexicographical relation between the strings:

return valuedescription
<0string1 is less than string2
0string1 is the same as string2
>0string1 is greater than string2

Portability.
  Defined in ANSI-C.

Example.

/* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Which is my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  printf ("Correct answer!\n");
  return 0;
}
Output:
Which is my favourite fruit? orange
Which is my favourite fruit? apple
Correct answer!

back to top


char *  strcpy ( char * dest, const char * src );

Copy string.
  Copies the content pointed by src to dest stopping after the terminating null-character is copied.
  dest should have enough memory space allocated to contain src string.

Parameters.

dest
Destination string. Should be enough long to contain string2.
string2
Null-terminated string to copy.

Return Value.
  dest is returned.

Portability.
  Defined in ANSI-C.

Example.

/* strcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}
Output:
str1: Sample string
str2: Sample string
str3: copy successful

back to top


size_t  strlen ( const char * string );

Return string length.
  Returns the number of characters in string before the terminating null-character.

Parameters.

string
Null-terminated string.

Return Value.
  The length of string.

Portability.
  Defined in ANSI-C.

Example.

/* strlen example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szInput[256];
  printf ("Enter a sentence: ");
  gets (szInput);
  printf ("Sentence entered is %u characters long\n",strlen(szInput));
  return 0;
}
Output:
Enter sentence: just testing
Sentence entered is 12 characters long

back to top


char *  strncat ( char * dest, const char * src, sizet_t num );

Append substring to string.
  Appends num characters of src string to dest string. If the terminating null-character appears in src string before num character have been appended, the function appends the null-character to dest and ends.
  The terminating null character in dest is overwritten by the first character of src. The resulting string includes a null-character at end.

Parameters.

dest
Pointer to a null-terminated string with enough space allocated to contain src plus num characters.
src
Null-terminated string containing characters to be appended.
num
Number of characters to be appended from src to dest.

Return Value.
  dest is returned.

Portability.
  Defined in ANSI-C.

Example.

/* strncat example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[20];
  char str2[20];
  strcpy (str1,"To be ");
  strcpy (str2,"or not to be");
  strncat (str1, str2, 6);
  puts (str1);
  return 0;
}
Output:
To be or not

back to top


int  strncmp ( const char * string1, const char * string2, sizet_t num );

Compare some characters of two strings.
  Compares the first num characters of string1 to the first num characters of string2.
  The comparison is performed character by character. If a character that is not equal in both strings is found the function ends and returns a value that determines which of them was greater.

Parameters.

string1
Null-terminated string to compare
string2
Null-terminated string to compare.
num
Maximum number of characters to compare.

Return Value.
  Returns a value indicating the lexicographical relation between the strings:

return valuedescription
<0string1 is less than string2
0string1 is the same as string2
>0string1 is greater than string2

Portability.
  Defined in ANSI-C.

Example.

/* strncmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[][5] = { "R2D2" , "C3PO" , "V4DR" , "C3A4" , "LUKE" };
  int n;
  printf ("Looking for human relations robots...\n");
  for (n=0 ; n&t;5 ; n++)
    if (strncmp (str[n],"C3**",2) == 0)
    {
      printf ("found %s\n",str[n]);
    }
  return 0;
}
Output:
Looking for human relations robots...
found C3PO
found C3A4

back to top


char *  strncpy ( char * dest, const char * src, sizet_t num );

Copy characters from one string to another.
  Copies the first num characters of src to dest.
  No null-character is implicitly appended to dest after copying process. So dest may not be null-terminated if no null-caracters are copied from src.
  If num is greater than the length of src, dest is padded with zeros until num.

Parameters.

dest
Destination string. Space allocated should be at least num characters long.
string2
Null-terminated string.
num
Number of characters to be copied.

Return Value.
  dest is returned.

Portability.
  Defined in ANSI-C.

Example.

/* strncpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]= "To be or not to be";
  char str2[6];
  strncpy (str2,str1,5);
  str2[5]='\0';
  puts (str2);
  return 0;
}
Output:
To be

back to top


Two implementations of the string length function.
int strlen1(char []);   // prototype
int strlen2(char *);    // prototype

char greeting1[] = "hi there!";
char *greeting2 = "hi there!";

int len1 = strlen1(greeting1);   // call
int len2 = strlen2(greeting2);   // size not needed due to null termination

...

int strlen1(char str[])    // definition
{
    int i = 0;
    while (str[i] != '\0')
        ++i;
    return i;
}

Discussion :

int strlen2(char *str)     // definition
{
    int i = 0;
    char *ptr = str;
    while (*ptr != '\0')
    {
        ++i;
	++ptr;
    }
    return i;
}

Discussion :

back to top

With C-style strings the programer must be careful to not access the arrays out of bounds. Consider string concatenation, combining two strings to form a single string. Is there room in the destination array for all the characters and the null? The C++ has a string class does not have these problems.