15 - C Strings

This chapter is going to introduce Strings. You are already aware of basic definition of strings as a sequence of characters. Strings can also be considered as a special type of array. We can say an array of characters is apparently known as strings. It is a one-dimensional array. This character array is terminated by null ('\0). Character in an array occupies one byte of memory. Last character is always '\0'. This special '\0' is known as Null character. Please make sure '0' and '\0' are not the same thing. Suppose you have the following string:

Figure - Logical representation of C String     

                  Figure -  Logical representation of C String

 

  Logically if we think this null character informs function that this is the end of sequence of characters which is to be considered as one string. There is a very simple way of string initialization where you do not have to explicitly represent null character to mark end of string. Here null character is automatically inserted and format is as follows:

char arrname[]=”DEBO”;

Usually, we have two types of strings and they are:

1.Fixed-length string

2.Variable length string

Fixed-length string is a type of string where length of string is fixed. We are aware of the storage requirement. No matter how many characters constitute the string, the space is fixed. Length of string cannot be changed, once defined. And spaces are usually added towards the end of string and they are apparently considered as non data characters. There are some disadvantages related to fixed length strings. For instance, if you have a large string and you have reserved smaller space then larger half of string will not be stored. In contrast, if you have a small string and you have reserved larger space then limited memory is wasted. Not only this, once defined, length of string cannot be changed. To solve these problems we have variable length strings.

Variable-length string is a type of string whose length is unknown as the name suggests. Storage container contracts and expands according to requirement of string length. But there has to be way to indicate the finish signal to compiler and for that purpose we have two general approaches and they are as follows:

1.Length controlled variable length string

2.Delimited variable length string

When we talk about length controlled string then as the name suggests, length information of string is stored as part of string. This information is stored as first byte and this is used as a counter. We can have any length of string which is in between 0-255 range. For example, “debo” strings would be stored as follows:

     Figure – C Length controlled string

                                              Figure – C Length controlled string  

In this scenario, there is one disadvantage and that is a if you have 4 byte length string as in the above example we will have one extra byte long string as length information is also a part of string so a 4 byte long string is actually going to occupy 5 bytes so this a sort of demerit when you have limited space and long strings to store. So we have one more option and that is delimited variable length which has a delimiter. Delimited string is the one which has NULL as the delimiter.

  Delimited variable length string

 

We are already aware of formatted and unformatted input/output so we shall move to string handling functions directly.

15.1 Function for String Handling

String is actually not a basic data type so we can say it as more or less derived data type. Using operators of C language we cannot actually handle or in other words manipulate strings. Hence C is equipped with string handling functions. These functions are included in “string.h” header file. We will have to terminate all the strings with the delimiter before using these string manipulation or string handling functions to get correct result. So let us have a glance on string handling functions which are as follows:

1) String Length, strlen(s): This function calculates the length of strings, All the constituent   characters are counted till null character is encountered or length is counted up to '\0' character excluding '\0' character in the length of   string. Format of strlen function is as follows:

               int strlen (char * s);

2) String Copy, strcpy(des, src): This function copies the content of one string into other. In other   words, the string in source represented by src is copied into destination string des. While string is copied from source to destination, the null character / delimiter ('\0') is also copied. After this process the contents which were originally present is destination string des are lost so it will only have contents which are copied from source string src. For this purpose, storage capacity or size of destination string should be larger and/or equal to source string. Format of this function is as follows:

              char *strcpy (char *des, char *src);

 

3) String Number Copy, strncpy(des,src,num):This is a different flavor of copy function. This function is responsible for copying num number of characters from source string src to destination string des. For instance, source string src is smaller than the specified num number of characters, in this case, source string is completely copied into destination string des and empty spaces are filled by nul characters ('\0'). In contrast, if source string src is larger than num number of characters, in that case, only num number of characters from source string src will be copied into destination string des and rest is discarded. And in the later case as destination string des will not have any delimiter or null character ('\0') so this scenario will result in an invalid string. Format of this function is as given below:

            char *strncpy (char *des, char *src, int num);

 

4) String Concatenate, strcat(str1,str2): This function is going to copy second string, str2 at the  end of first string, str1. Here, the size of first string, str1  should be large enough to store first string, str1 followed by second string, str2. Delimiter ('\0') or null character of first string, str1 is replaced by first character of second string, str2. Format of this function is as given below:

           char *strcat(char *str1, char *str2);

3)String Number Concatenate, strncat(str1,str2,num): This function is an advanced flavor of strcat function. This works similarly as strcat function works except some additional advantage of having a integer value which works more or less like an counter, num. When length of second string, str2 is smaller than the integer value specified as num then this function is going to copy entire second string, str2 at the end of first string, str1. Other possibility is to have the length of second string, str2 to be larger than number, num. In this case, first num number of characters of second string, str2 is added at the end of first string, str1 terminated with delimiter or null character ('\0') so that it results in a valid string. Format of this function is as follows:

           char *strncat (char *str1, char *str2, int num);

4)String Compare, strcmp(str1,str2): This function is responsible for comparing two strings. This function starts comparison from first character of first string, str1 and continues until delimiter or null character ('\0') of first character is encountered or characters in both strings start to differ from each other. This function returns integer value. When this function returns zero (0) value then this implies both strings are equal. This function returns positive value, when first string, str1 is larger than second string, str2. This function returns negative value, when first string, str1 is less than second string, str2. Format of this function is as follows:

            int strcmp (char *str1, char *str2);

5)String Number Compare, strncmp(str1, str2, num): This function is again a different flavor of strcmp. The only difference is this function will compare only the num number of character in both strings namely, first string, str1 and second string, str2. Comparison continues until we exhaust the string, that is we reach the end or characters start differing from each other or comparison of num number characters is done. This function returns integer value. This function also returns zero (0) value when both the strings are equal. Function will return positive value, if first string, str1 is larger than second string, str2. And this function will return negative value when first string, str1 is smaller than second string, str2. Format of this function is as follows:

             int strncmp (char *str1, char *str2);

 

6) String containing character, strchr(str1,c): This function finds the first presence of character, c from the beginning of the string, str1 and then  returns pointer which points to the character if it is successful. Otherwise it results NULL value if function fails. Format of this function is as follows:

             char *strchr (char *str1, char c);

 

7) String in string, strstr(str1, str2): This function is similar to strchr in a way that it searches  first presence of the sub string, str2 in string, str1 and  returns pointer to the character if it is successful otherwise this function also returns NULL value. Format of this function is as follows:

          char *strstr( char *str1, char *str2);

 

8) String Span, strspn (str1, str2): This function compares each character of first string, str1 with  each character of second string, str2. This comparison is  carried out from left to right order with constituents of second string, str2. As soon as character in first string, str1 does stops matching with any of the constituent character of second string, str2, function stops searching. Function returns an integer value. This function will return the number of characters in first string, str1 which matched with second string, str2 successfully and it will return zero (0), if no characters in first string, str1 matches with second string, str2. Format of this function is as given below:

          int strspn (char *str1, char *str2);

Let us consider an example program to understand the working principle of strings in C.

 

/* Program to illustrate strings and string handling function */ 

# include <stdio.h>
# include <ctype.h>
# include <conio.h>
# include <string.h>

void main()
{
 clrscr();
 char string[30], c;
 int i, count_vowel, count_consonant;  

 printf("Please enter the sentence\n");
 gets(string);

 count_vowel=count_consonant=0;
 for (i=0; i<strlen(string); i++)
    {
    if(isalpha(string[i]))
        { 
          c=tolower(string[i]);

          if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
            count_vowel ++;
          else
           count_consonant++;
        }
    }
  printf("Number of vowels present in this sentence is = %d\n", count_vowel);
  printf("Number of consonants present in this sentence is =%d\n", count_consonant);
  getch();
}

 

                C Program to illustrate strings and string handling function

 Compiled output of C Program to illustrate strings and string handling function

             Compiled output of C Program to illustrate strings and string handling function

Output of C Program to illustrate strings and string handling function

                         Output of C Program to illustrate strings and string handling function

Folks! With this we conclude strings. Next chapter is going to introduce structures. Thank you.

Like us on Facebook