Null-Terminated Strings


By far the most common use of the one-dimensional array is as a character string, C supports two types of strings. The first is the null-terminated string, which is a null-terminated character array. Thus a null-terminated string contains the characters that comprise the string followed by a null. This is the only type of string defined by C, and it is still the most widely used. Sometimes null-terminated strings are called C-strings. C++ also defines a string class, called string, which provides an object-oriented approach to string handling.

When declaring an array of characters containing a null-terminated string, you must declare it as a longer character than the largest string you hold. For example, to declare an array ch that can hold a 10-character string, you type

char ch[11];

This makes room for the null at the end of the string.

When you use a quoted string constant in your program, you are also creating a null-terminated string. A string constant is a list of characters enclosed in double-quotes. For example,

"hello world"

You do not need to manually add a null at the end of the string constant - the compiler does this for you automatically.

The most common functions are those that support a wide range of functions that handle null-terminated strings.

Name Meaning
strcpy(s1,s2) Copies s2 into s1.
strcat(s1,s2) Concatenates s2 onto the end of s1.
strlen(s1) Returns the length of s1.
strcmp(s1,s2) Return 0 if s1 and s2 are the same.
strchr(s1,ch) Returns a pointer to the first occurrence of ch in s1.
strstr(s1,s2) Returns a pointer to the first occurrence of s2 in s1.

Sample Program

Program
#include<stdio.h>
#include<string.h>

int main() {
  char s1[20] = "hello";
  char s2[20] = "world";
  char s3[5] = "e";
  
  printf("strlen(s1) : %d\n",strlen(s2));
  if(!strcmp(s1,s2))
   printf("strcmp(s1,s2) : Two strings are equal\n",s1,s2);
  else
   printf("strcmp(s1,s2) : Two strings are not equal \n");
  if(strchr(s1,'o'))
   printf("strchr(s1,'o') : Found in s1\n");
  else
   printf("strchr(s1,'o') : Not found in s1\n");
  if(strstr(s1,s3))
   printf("strstr(s1,s3) : Found in s1\n");
  else
   printf("strstr(s1,s3) : Not found in s1\n");
  printf("strcat(s1,s2) : %s\n",strcat(s1,s2));
  printf("strcpy(s1,s2) : %s\n",strcpy(s1,s2));
  return 0;
}

Remember that, strcmp() returns false if the strings are equal. Be sure to use the logical operator! to reverse the condition, as just shown, if you are testing for equality.


Although C ++ has defined a string class, null-terminated strings are still widely used in existing programs. They will probably be of widespread use because they provide a high level of efficiency and give the programmer detailed control over stream activities. However, for many string-handling tasks, the C ++ string class provides a convenient alternative.


s