8 Strings and Standard Functions – Programming in C, 3/e, 3rd Edition

CHAPTER 8

Strings and Standard Functions

Chapter Outline
8.1  Introduction

Characters are the basic requirement of any program. A program contains statements and statements are built with words that has specific meaning to be understood by the compiler. In C language, a sequence of characters, digits and symbols enclosed within double quotation marks is called a string. The string is always declared as character array and its elements are stored in contiguous memory locations.

In other words, in C, a string is defined as an array of characters. To manipulate text such as words and sentences, normally strings are used. Every string is terminated with ‘\0’ (NULL) character. The NULL character is a byte with all bits at logic zero. Hence, its decimal value is zero. A pointer can access the string. The value of the string is its base address, i.e. addresses of the first character. When a string is created, a few compilers place the string in the memory where it cannot be modified.

An example of a string is as follows:

char name[]={‘I’,‘N’,‘D’,‘I’,‘A’,‘\0’};

Each character of the string occupies 1 byte of memory. The last character is always ‘\0’. It is not compulsory to write ‘\0’ in string. The compiler automatically puts ‘\0’ at the end of the character array or string. The characters of a string are stored in contiguous (neighbouring) memory locations. In the above example, the compiler automatically determines the size of the array. Table 8.1 shows the storing of string elements in contiguous memory locations.

Table 8.1   Memory map of a string

While storing characters in a string array one should confirm if the array length is large enough to store the given string. Moreover, double quotes can be used to store a word or constants with type char. The length of the characters in “MAHARASHTRA” is 11 but in C, the character array should have a length of 12. One more character is needed at the end of string, which is called a null character.

The declaration is as follows:

char name[12]=“MAHARASHTRA”

or

char name[12]={‘M’,‘A’,‘H’,‘A’,‘R’,‘A’,‘S’,‘H’,‘T’,‘R’,‘A’,‘\0’};

C permits the storage of string to any length. However, if a string exceeds the limit of a character array, it will overwrite the data beyond the array.

8.2  Declaration and Initialization of String

The syntax for initialization of a string is as follows:

char name[ ]=“INDIA”;

The C compiler inserts the NULL (\0) character automatically at the end of the string. So initialization of the NULL character is not essential. Even if null is added at the end of string, compiler does not throw any error.

By initializing character arrays as per the following ways, the programmer can see the output:

  1. char name[6]={‘S’,‘A’,‘N’,‘J’,‘A’,‘Y’};
  2. char name[7]={‘S’,‘A’,‘N’,‘J’,‘A’,‘Y’};

In case (a) the output will not be ‘SANJAY’ as it contains some garbage value at the end of SANJAY. Array index/size in this example is initialized with [6], which is exactly equal to the number of characters within the braces. The NULL character must be included at the end of string and hence, the array index/size must be [7] instead of [6] as given in statement (b).

  8.1   Write a program to display the output when the account of NULL character is not considered.

 

void main()

{

char name1[6]={‘S’,‘A’,‘N’,‘J’,‘A’,‘Y’};

clrscr();

printf(“Name1 = %s”,name1);

getche();

}

OUTPUT:

   Name1 = SANJAYabdn12

Explanation:

The output of the above program would be SANJAY followed by some garbage values. To get the correct result, the argument must be [7] instead of [6]. The output can be seen as given below after changing the size [7] in place of [6].

The output will be: SANJAY

The array size must be equal to the number of characters of the word + NULL character. In case the NULL character is not taken into account (statement (a)) the string followed by the first string (statement (b)) will be displayed. The output can be observed by executing the following program.

  8.2   Write a program to display successive string in case first string is not terminated with NULL character.

 

void main()

{

char name1[6]={‘S’,‘A’,‘N’,‘J’,‘A’,‘Y’};

char name2[7]={‘S’,‘A’,‘N’,‘J’,‘A’,‘Y’};

clrscr();

printf(“Name1 = %s”,name1);

printf(“\nName2 = %s”,name2);

}

OUTPUT:

Name1 = SANJAYSANJAY

Name2 = SANJAY

Explanation:

The NULL character has not been considered in the first statement. The compiler reads the second string immediately followed by the first string because the end of first string is not identified. Because of this, the second string is printed followed by the first string. Hence, the argument must include the account of the NULL character.

Simple string programs are as follows.

  8.3   Write a program to print ‘WELCOME’ by using different syntax of initialization of array.

 

void main()

{

char arr1[9]={‘W’,‘E’,‘L’,’ ’,‘C’,‘O’,‘M’,‘E’,‘\0’};

char arr2[9]=“WELCOME”;

char arr3[9]= {{‘W’},{‘E’},{‘L’},{’ ’},{‘C’},{‘O’},{‘M’},{‘E’}};

clrscr();

printf(“\nArray1 = %s”,arr1);

printf(“\nArray2 = %s”,arr2);

printf(“\nArray3 = %s”,arr3);

}

OUTPUT:

Array1 = WEL COME

Array2 = WELCOME

Array3 = WEL COME

Explanation:

The string elements can be initialized individually with enclosing single quote and curly braces. The curly braces are optional. While initializing individual elements, they must be separated by a comma. This is done in the first and third statements. Also it can be initialized with double-quotation marks and this is done in the second statement.

8.3  Display of Strings with Different Formats

The printf() function is used for displaying various data types. The printf() function with %s format is to be used for displaying a string on the screen. Various printf() formats are shown in Table 8.2, when char text[15]=“PRABHAKAR”;

Table 8.2   String formats with different precision

Sr. No.

Statement

Output

1.

printf (“%s\n”,text);

PRABHAKAR

2.

printf (“%.5s\n”,text);

PRABH

3.

printf (“%.8s\n”,text);

PRABHAKA

4.

printf (“%.15s\n”,text);

PRABHAKAR

5.

Printf (“%−10.4s\n”,text);

PRAB

6.

Printf (“%11s”,text);

  PRABHAKAR

  1. The 1st statement displays the output ‘PRABHAKAR’. The entire string is displayed with the first statement.
  2. We can also specify the precision with character string, which is to be displayed. The precision is (the number of characters to be displayed) provided after the decimal point. For instance in the 2nd statement in Table 8.2   the first five characters are displayed. Here, the integer value 5 on the right side of the decimal point specifies the five characters to be displayed.
  3. In the 3rd statement, the first eight characters are displayed.
  4. Statement number four displays the entire string.
  5. The 5th statement with minus () sign (e.g. %−10.4s) displays the string with left justified.
  6. When the field length is less than the length of the string the entire string is printed. When it is greater than the length of the string, blank spaces are initially printed followed by the string. This effect can be seen in the 6th statement.
  7. When the number of characters to be displayed is specified as zero after decimal point nothing will be displayed.

A few examples are illustrated below giving the effects of various formats of strings.

  8.4   Write a program to display the string ‘PRABHAKAR’ using various printf() format specifications.

 

void main()

{

char text[15]=“PRABHAKAR”;

clrscr();

printf(“%s\n”,text);

printf(“%.5s\n”,text);

printf(“%.8s\n”,text);

printf(“%.15s\n”,text);

printf(“%−10.4s\n”,text);

printf(“\n%11s”,text);

}

OUTPUT:

PRABHAKAR

PRABH

PRBHAKA

PRABHAKAR

PRAB

  PRABHAKAR

  8.5   Use the while loop and print out the elements of the character array.

 

void main()

{

char text[]=“HAVE A NICE DAY”;

int i=0;

clrscr();

while(i<15)

{

  printf(“%c”,text[i]);

  i++;

}

}

OUTPUT:

HAVE A NICE DAY

Explanation:

In this program, while loop is used for printing the characters up to the length of 15; thereafter it terminates when variable ‘i’ reaches 15.

  8.6   Given below is an example in which the string elements are displayed. Use the while loop and print out the elements of the character array. Take the help of NULL (‘\0’) character.

 

void main()

{

char text[]=“HAVE A NICE DAY”; int i=0;

clrscr();

while(text[i]!=‘\0’)

{

  printf(“%c”,text[i]);

  i++;

}

getch();

}

OUTPUT:

HAVE A NICE DAY

Explanation:

It is not needed to give the array size as given in the previous programs. One can display the character string without knowing the length of the string. As we know that every character array always ends with NULL (‘\0’) character, by using the NULL character in while loop we can write a program to display the string.

8.4  String Standard Functions

C compiler supports a large number of string handling library functions. Table 8.3 provides the list of many frequently used functions and their description. The header file string.h is to be initialized whenever standard library function is used. In other words, the string handling functions are given in string.h.

Table 8.3   Standard C string library functions

Functions

Description

strlen()

Determines the length of a string.

strcpy()

Copies a string from the source to destination.

strncpy()

Copies characters of a string to another string up to the specified length.

strcmp()

Compares characters of two strings (function discriminates between small and capital letters)

stricmp()

Compares two strings (function does not discriminate between the small and capital letters).

strncmp()

Compares characters of two strings up to the specified length.

strnicmp()

Compares characters of two strings up to the specified length. Ignores case.

strlwr()

Converts uppercase characters of a string to lowercase.

strupr()

Converts lowercase characters of a string to uppercase.

strdup()

Duplicates a string.

strchr()

Determines the first occurrence of a given character in a string.

strrchr()

Determines the last occurrence of a given character in a string.

strstr()

Determines the first occurrence of a given string in another string.

strcat()

Appends source string to the destination string.

strncat()

Appends the source string to the destination string up to a specified length.

strrev()

Reversing all characters of a string.

strset()

Sets all characters of a string with a given argument or symbol.

strnset()

Sets specified numbers of characters of a string with a given argument or symbol.

strspn()

Finds up to what length two strings are identical.

strpbrk()

Searches the first occurrence of the character in a given string and then displays the string starting from that character.

We shall elaborate the above-cited functions by providing a few examples of each of them. Without using the standard functions, we can also write the programs. A few such programs are briefly described.

 

strlen()function

This function counts the number of characters in a given string. The syntax of the function is strlen (char*S); A program in this regard is illustrated below.

  8.7   Write a program to count the number of characters in a given string.

 

# include <string.h>

void main()

{

char text[20];

int len;

clrscr();

printf(“Type Text Below.\n”);

gets(text);

len=strlen(text);

printf(“Length of String =%d”,len);

}

OUTPUT:

Type Text Below.

Hello

Length of String = 5

Explanation:

In the above program, strlen() function is called. Through the text array base address will be sent and this function returns the length of the string. It counts the string length Without the NULL character.

  8.8   Write a program to read a name through the keyboard. Determine the length of the string and find its equivalent ASCII codes.

 

# include <string.h>

void main()

{

static char name[20];

int i,l;

clrscr();

printf(“Enter your name :”);

scanf(“%s”,name);

l=strlen(name);

printf(“Your Name is %s &”, name);

printf(“it contains %d characters.”,l);

printf(“\nName & it’s Ascii Equivalent.\n”);

printf(“==== = === ===== ==========\n”);

for(i=0;i<l;i++)

printf(“\n %c\t\t%d”,name[i],name[i]);

getch();

}

OUTPUT:

Enter your name : SACHIN

Your Name is SACHIN & it contains 6 characters.

Name & it’s Ascii Equivalent.

====  = ====

===== ==========

S

83

A

65

C

67

H

72

I

73

N

78

Explanation:

In the above program, a string is entered. The string length is determined using the strlen() function. The for loop is used for displaying characters and their equivalent ASCII codes.

  8.9   Write a program to remove the occurrences of ‘The’ word from the entered text.

 

# include <string.h>

void main()

{

static char line[80],line2[80];

int i,j=0,l;

clrscr();

printf(“Enter Text Below.\n”);

gets(line);

l=strlen(line);

for(i=0;i<=l;i++)

{

  if (i>=l−4 || l==3 && line[l−4]==‘ ’ && line[l−3]==‘t’ && line[l−2]==‘h’ && line[l−1]==‘e’)

  continue;

  if(line[i]==‘t’ && line[i+1]==‘h’ && line[i+2]==‘e’ && line[i+3]==‘ ’)

  {

    i+=2;

    continue;

  }

  else

  {

    line2[j]=line[i];

    j++;

  }

}

printf(“\n Text with ‘the’   : %s”, line);

printf(“\n Text without ‘the’ : %s”,line2);

getch();

}

OUTPUT:

Enter Text Below.

Printf write data to the screen.

Text with ‘the’  : Printf write data to the screen.

Text without ‘the’ : Printf write data to screen

Explanation:

The first if condition is identifying the appearance of ‘the’ at the end of text as well as when the string contains only ‘the’. If it is found the program terminates.

The second if condition in the above program, also identifies the appearance of ‘the’ word in the text. If it do not found the word ‘the’, elements of the first array are copied to the second array as it is. If the word ‘the’ is found program will continue to loop and never reach the statement line2[j]=line[i];.

  8.10   Write a program to delete all the occurrences of vowels in a given text. Assume that the text length will be of one line.

 

void main()

{

char line[80],line2[80];

int i,j=0;

clrscr();

printf(“Enter Text Below.\n”);

gets(line);

for(i=0;i<80;i++)

{

  if(line[i]==‘a’ || line[i]==‘e’ || line[i]==‘i’ || line[i]==‘o’ || line[i]==‘u’|| line[i]=‘A’ || line[i]=‘E’ || line[i]=‘I’ || line[i]=‘O’ || line[i]=‘U’)

  continue;

  else

  {

    line2[j]=line[i];

    j++;

  }

}

printf(“\n Text with Vowels : %s”, line);

printf(“\n Text without Vowels : %s”,line2);

}

OUTPUT:

Enter Text Below.

Have a nice day.

Text with Vowels : Have a nice day.

Text without Vowels : Hv nc dy.

Explanation:

The logic used here is the same as described in the previous program. The if statement checks the occurrence of vowels (a, e, i, o, u, A, E, I, O & U). If vowels are found loop is continued, otherwise elements are copied. Thus, vowels are skipped in the final output.

  8.11   Write a program to find the no. of characters in a given string including and excluding spaces.

 

void main()

{

char text[20];

int i=0,len=0,ex=0;

clrscr();

printf(“Enter Text Here :”);

gets(text);

while(text[i]!=‘\0’)

{

  if(text[i]==‘ ’)

  ex++;

  else

  len++;

  i++;

}

printf(“\nLength of String Including Spaces. : %d”,len+ex);

printf(“\nLength of String Excluding Spaces. : %d”,len);

}

OUTPUT:

Enter Text Here :

Time is Money.

Length of String Including Spaces. : 13

Length of String Excluding Spaces. : 11

Explanation:

In the above program, some text is entered. The if statement within the while loop checks every element of string, and if space is observed the counter variable ‘ex’ is incremented otherwise variable ‘len’ is incremented. Thus, at the end the variable ‘ex’ contains the total number of spaces in the string and the variable ‘len’ contains the length of the string excluding spaces. The length including spaces is calculated by adding both the variables.

  8.12   Write a program to display the length of the entered string and display it as per the output shown.

 

# include <string.h>

void main()

{

int c,d;

static char string[12];

int ln;

printf(“Enter a String :”);

gets(string);

ln=strlen(string);

clrscr();

printf(“\n Length of given string :%d”,ln);

printf(“\n Sequence of characters displayed on screen”);

printf(“\n ======== == ========== ========= == ======”);

printf(“\n\n\n”);

for(c=0;c<=ln−1;c++)

{

  d=c+1;

  printf(“\t%.*s\n”,d,string);

}

for(c=ln−1;c>=0;c−−)

{

  d=c+1;

  printf(“\t%.*s\n”,d,string);

}

}

OUTPUT:

Enter a String : HAPPY

Length of given string : 5

Sequence of characters displayed on screen

======== == ========== ========= == ======

H

HA

HAP

HAPP

HAPPY

HAPPY

HAPP

HAP

HA

H

Explanation:

In the above program, the string is entered and its length is calculated. The first for loop displays characters from left to right. It next adds one character in each successive line. The first line displays the first character, the second two characters and so on.

The second for loop displays characters from right to left. It removes the right-most character in each successive line.

Here, in the printf() the asterisk (*) used after decimal plays an important role in displaying the characters. It requires an integer argument. It displays only the given number of characters from the string.

 

strcpy() function

This function copies the contents of one string into another.

The syntax of strcpy() is strcpy(char *s2,char *s1);

where

s1 is the source string; s2 is the destination string and s1 is copied to s2.

In many programs, we copy the contents of one string to other. Given below is an example which is based on the strcpy() function.

  8.13   Write a program to copy the contents of one string to another by using strcpy().

 

# include <string.h>

void main()

{

char ori[20],dup[20];

clrscr();

printf(“Enter Your Name :”);

gets(ori);

strcpy(dup,ori);

printf(“Origional String : %s”,ori);

printf(“\nDuplicate String : %s”,dup);

}

OUTPUT:

Enter Your Name : SACHIN

Original String : SACHIN

Duplicate String : SACHIN

Explanation:

In the above example, we have declared two arrays namely ori[20] and dup[20]. The function strcpy() copies characters of ori[] to dup[]. The characters are copied one by one from source string (ori [20]) to destination string (dup[20]).

Program without strcpy() function

  8.14   Write a program to copy the contents of one string to another, without the strcpy() function.

 

# include <string.h>

void main()

{

char ori[20],dup[20];

int i;

clrscr();

printf(“Enter Your Name :”);

gets(ori);

for(i=0;i<20;i++)

dup[i]=ori[i];

printf(“Original String : %s”,ori);

printf(“\nDuplicate String : %s”,dup);

}

OUTPUT:

Enter Your Name : SACHIN

Original String : SACHIN

Duplicate String : SACHIN

Explanation:

In the above program, we also have declared two arrays namely ori[20] and dup[20]. Instead of using the strcpy() function, by using the for loop elements of source array are copied into the destination array one by one.

 

strncpy() function

strncpy() function performs the same task as strcpy(). The only difference between them is that the former function copies specified length of characters from the source to destination string, whereas the latter function copies the whole source string to destination string. The syntax of the function is

strncpy(char *destination ,char *source, int n);

where n is the argument.

A simple example is illustrated below.

  8.15   Write a program to copy source string to destination string up to a specified length. Length is to be entered through the keyboard.

 

# include <string.h>

void main()

{

char str1[15], str2[15];

int n;

clrscr();

printf(“Enter Source String :”);

gets(str1);

printf(“Enter Destination String :”);

gets(str2);

printf(“Enter Number of Characters to Replace in Destination String :”);

scanf(“%d”,&n);

strncpy(str2,str1,n);

printf(“Source String :%s”,str1);

printf(“\nDestination String :%s”,str2);

}

OUTPUT:

Enter Source String  : wonderful

Enter Destination String  : beautiful

Enter Number of Characters to Replace in Destination String : 6

Source String  : wonderful

Destination String  : wonderful

Explanation:

In the above program, two strings are read from terminal. The number of characters to replace in the destination string from source string is also entered. After obtaining these three arguments the strncpy() function replaces the destination string with the number of characters (argument). The source string characters are ‘wonderful’ and the destination ‘beautiful’ before the use of strncpy(). After execution, the first six characters of destination string (‘beauti’) are replaced with first six characters of source string (‘wonder’). The output of the program is as shown above.

 

stricmp() function

The syntax of the function is stricmp(char *s1,char *s2);

This function compares two strings. The characters of the strings may be in lowercase or uppercase; the function does not discriminate between them. That is, this function compares two strings without case. If the strings are the same it returns to zero otherwise non-zero value.

  8.16   Write a program to compare the two strings using the stricmp() function. If strings are identical display ‘The Two Strings are Identical’ otherwise ‘The Strings are Different’.

Note: stricmp()function compares two strings character by character and returns 0 if the strings are identical otherwise non-zero value. This function does not discriminate between small and capital letters.

 

void main()

{

char sr[10],tar[10];

int diff;

clrscr();

printf(“Enter String(1) : ”);

gets(sr);

printf(“Enter String(2) : ”);

gets(tar);

diff=stricmp(sr,tar);

if(diff==0)

puts(“The Two Strings are Identical.”);

else

puts(“The Two Strings are Different”);

getche();

}

OUTPUT:

Enter String(1) : HELLO

Enter String(2) : hello

The Two Strings are Identical.

Explanation:

In the above program, two strings are entered. Both the strings are compared using the stricmp() function. If both the strings are identical it returns 0 otherwise non-zero value. The returned value of the stricmp() function is assigned to variable ‘diff’. The if condition checks the value of variable ‘diff’ and respective message is displayed.

  8.17   Write a program to perform the following:

  1. Display the question “What is the Unit of Traffic?”
  2. Accept the answer.
  3. If the answer is wrong (Other than Earlang) display “Try again!” & continues to answer.
  4. Otherwise, if it is correct “Earlang” display the message “Answer is correct”.
  5. If the user gives correct answer in first two attempts the program will terminate.
  6. If the user fails to provide correct answer in three attempts the program it self gives the answer.

 

# include <process.h>

void main()

{

char ans[8];

int i;

clrscr();

for(i=1;i<=3;i++)

{

  printf(“\nWhat is the Unit of Traffic?”);

  scanf(“%s”,ans);

  fflush(stdin);

  if(stricmp(ans,”Earlang”)==0)

  {

    printf(“\nAnswer is Correct.”);

    exit(1);

  }

  else

  if(i<3)

  printf(“\n Try Again !\n”);

}

clrscr();

printf(“\nunit of Traffic is Earlang.”);

}

OUTPUT:

What is the Unit of Traffic ? Earlan

Try Again !

What is the Unit of Traffic ? Earlam

Try Again !

What is the Unit of Traffic ? Earlang

Answer is Correct.

Explanation:

In the above program stricmp() function is used for comparing character array ans[] and ‘Earlang’. If function returns 0 (zero) the message displayed will be ‘Answer is Correct’. In case, the answer is wrong the message displayed will be ‘Try again!’. Three attempts are provided using the for loop for answering the question. The fflush() function is used for clearing the buffer.

 

strcmp() function

strcmp(): One can also use strcmp() function instead of stricmp(). The only difference between them is the former function discriminates between small and capital letters whereas the latter does not. The output of the above program after strcmp() in place of stricmp() will be as follows:

Enter String(1) : HELLO

Enter String(2) : hello

The Two Strings are Different.

The above function compares two strings for finding whether they are the same or different. Characters of these strings are compared one by one. In case of a mismatch the function returns to non-zero value, otherwise it returns zero, i.e. when the two strings are the same strcmp() returns the value zero. If they are different it returns the numeric difference between the ASCII values of non-matching characters.

 

strncmp() function

Comparison of two strings can be made up to a certain specified length. The function used for this is strncmp(). This function is the same as strcmp() but it compares the character of the string to the specified length. The syntax of this function is as follows:

strncmp(char *source, char *target, int argument);

where the argument is the number of characters up to which the comparison is to be made.

  8.18   Write a program to compare two strings up to specified length.

 

# include <string.h>

void main()

{

char sr[10],tar[10];

int n,diff;

clrscr();

printf(“Enter String(1) : ”);

gets(sr);

printf(“Enter String(2) : ”);

gets(tar);

printf(“\nEnter Length up to which comparison is to be made ”);

scanf(“%d”,&n);

diff=strncmp(sr,tar,n);

if(diff==0)

printf(“The Two Strings are Identical up to %d characters.”,n);

else

puts(“The Two Strings are Different.”);

getche();

}

OUTPUT:

Enter String(1) : HELLO

Enter String(2) : HE MAN

Enter Length up to which comparison is to be made : 2

The Two Strings are Identical up to 2 characters.

Explanation:

One can also use strnicmp() function instead of strncmp(). The only difference between them is that, the former function discriminates between small and capital letters whereas the latter does not. The output of the above program after strnicmp() in place of strncmp() will be as follows:

Enter String(1) : HELLO

Enter String(2) : HE MAN

The two strings are identical up to two characters.

Similarly, a program without using strcmp() can be developed which is as given below.

  8.19   Write a program to enter the two strings and compare them without using any standard function. Determine whether the strings are identical or not. Also display the number of position where the characters are different.

 

# include <string.h>

void main()

{

static char sr[10],tar[10];

int diff=0,i;

clrscr();

printf(“Enter String(1) : ”);

gets(sr);

printf(“Enter String(2) : ”);

gets(tar);

for(i=0;i<10;i++)

{

  if(sr[i]==tar[i])

  continue;

  else

  {

    printf(“%c %c\n”, sr[i], tar[i]);

    diff++;

  }

}

if(strlen(sr)==strlen(tar) && diff==0)

puts(“\nThe Two Strings are Identical”);

else

printf(“\nThe Two Strings are Different at %d places.”,diff);

getche();

}

OUTPUT:

Enter String(1) : BEST LUCK

Enter String(2) : GOOD LUCK

G B

O E

O S

D T

The Two Strings are Different at 4 places.

Explanation:

In the above program, two strings up to 10 characters can be entered. The if condition within the for loop checks corresponding characters of both the strings. If they are identical the loop is continued. Otherwise, counter variable ‘diff’ is incremented and different characters of two strings are displayed. The last if condition checks the variable ‘diff’ and displays respective messages.

 

strlwr() function

This function can be used to convert any string to lowercase. When you are passing any upper case string to this function it converts into lowercase. The standard syntax of strlwr() is as follows:

strlwr(char *string);

  8.20   Write a program to convert the uppercase string to lowercase using strlwr().

 

# include <string.h>

void main()

{

char upper[15];

clrscr();

printf(“\nEnter a string in Upper case :”);

gets(upper);

printf(“After strlwr() : %s”, strlwr(upper));

}

OUTPUT:

Enter a string in Upper case : ABCDEFG

After strlwr() : abcdefg

Explanation:

In this program string is entered in capital letters. The string is passed to the function strlwr(). This function converts the string to lower case.

 

strupr() function

This function is the same as strlwr() but the difference is that strupr() converts lowercase strings to uppercase strings. The syntax of this function is strupr(char *string);

  8.21   Write a program to convert the lowercase string to upper case using strupr().

 

# include <string.h>

void main()

{

char upper[15];

clrscr();

printf(“\n Enter a string in Lower Case :”);

gets(upper);

printf(“After strupr() : %s”, strupr(upper));

}

OUTPUT:

Enter a string in Lower Case : abcdefg

After strupr() : ABCDEFG

Explanation:

In this program a string is entered. The string is passed to the function strupr(). This function converts the string to uppercase.

 

strdup() function

This function is used for duplicating a given string at the allocated memory which is pointed by the pointer variable. The syntax of this function is text2=strdup(text1).

Where text1 is a string and text2 is a pointer.

  8.22   Write a program to enter the string and get its duplicate. Use the strdup() function.

 

# include <string.h>

void main()

{

char text1[20],*text2;

clrscr();

printf(“Enter Text :”);

gets(text1);

text2=strdup(text1);

/* pointer *text2 is initialized to the address of text1 through strdup() function. */

printf(“Original String = %s\nDuplicate String = %s”,text1,text2);

}

OUTPUT:

Enter Text : Today is a Good Day.

Original String = Today is a Good Day.

Duplicate String = Today is a Good Day.

Explanation:

In the above program character array text1[] and pointer variable *text2 are declared. A string is entered in character array text1[]. The strdup() function copies the contents of text1[] array to pointer variable *text2. The printf() function displays the contents of both the variables which are the same.

 

strchr() function

This function returns the pointer position to the first occurrence of the character in the given string. The format of this function is chp=strchr(string,ch);

Where string is a character array, ch is a character variable and chp is a pointer which collects address returned by the strchr() function. The syntax of this function is strchr(char*string, char character);

  8.23   Write a program to find first occurrence of a given character in a given string. Use the strchr() function.

 

# include <string.h>

void main()

{

char string[30],ch,*chp;

clrscr();

printf(“Enter Text Below :”);

gets(string);

printf(“\nCharacter to find :”);

ch=getchar();

/* returns a pointer to the first occurrence of the given character in*/

/* pointer chp, if given character is not found strchr() returns null.*/

chp=strchr(string,ch);

if(chp)

printf(“Character %c found in string.”,ch);

else

printf(“Character %c not found in string.”,ch);

}

OUTPUT:

Enter Text Below: Hello Beginners.

Character to find : r

Character r found in string.

OR

  8.24   Write a program to find the first occurrence of a given character in a given string. Find the memory location where the character occurs. Use the strchr() function.

 

# include <string.h>

void main()

{

char line1[30],line2,*chp;

int i;

clrscr();

puts(“Enter Text :”);

gets(line1);

puts(“Enter Character to find from the text :”);

line2=getche();

for(i=0;i<strlen(line1);i++)

printf(“\n%c %u”,line1[i],&line1[i]);

chp=strchr(line1,line2);

if(chp)

{

  printf (“\nAddress of first %c returned by strchr() is %u“,line2,chp);

}

else

printf(“%c character is not present in Given String”,line2);

}

OUTPUT:

Enter Text : HELLO

Enter Character to find from the text : L

H 4032

E 4033

L 4034

L 4035

O 4036

Address of first L returned by strchr() is 4034.

Explanation:

This function finds the memory location where, the first occurrence of a given character is found in a given string. When it finds the character the program terminates and the strchr() function provides the address of that character. The strchr() function returns the memory address of the first occurred character, i.e. it returns the memory address, which is collected by the pointer variable.

Note: In place of strchr() one can use strrchr(). The difference between them is that strchr() searches the occurrence of a character from the beginning of the string whereas strrchr() searches the occurrence of a character from the end (reverse).

 

strstr() function

This function finds the second string in the first string. It returns the pointer location from where the second string starts in the first string. In case the first occurrence in the string is not observed, the function returns a NULL character.

The syntax of this function is strstr (char *string1,char *sring2);

  8.25   Write a program using strstr() function for occurrence of second string in the first string.

 

# include <string.h>

void main()

{

char line1[30],line2[30],*chp;

clrscr();

puts(“Enter Line1 :”);

gets(line1);

puts(“Enter Line2 :”);

gets(line2);

chp=strstr(line1,line2);

if(chp)

printf(“\‘%s\’ String is present in Given String.”,line2);

else

printf(“\‘%s\’ String is not present in Given String.”,line2);

}

OUTPUT:

Enter Line1 : INDIA IS MY COUNTRY.

Enter Line2 : INDIA

‘INDIA’ String is present in Given String.

 

strcat() function

This function appends the target string to the source string. Concatenation of two strings would be done using this function. The syntax of this function is strcat(char *text1,char *text2);

  8.26   Write a program to append the second string at the end of the first string using the strcat() function.

 

# include <string.h>

void main()

{

char text1[30], text2[10];

puts(“Enter Text1 :”);

gets(text1);

puts(“Enter Text2 :”);

gets(text2);

strcat(text1,“ ”);

strcat(text1,text2);

clrscr();

printf(“%s\n”, text1);

}

OUTPUT:

Enter Text1 : I am

Enter Text2 : an Indian

I am an Indian

Explanation:

In the above example, two strings are entered in the character array text1[] and text2[]. The strcat() function concatenates both the strings, i.e. the second string is appended in the first string. The printf() function displays the contents of the text1[] which is the concatenation of the two strings.

  8.27   Write a program to concatenate two strings without the use of the standard function.

 

# include <string.h>

void main()

{

char name[50],fname[15],sname[15],lname[15];

int i,j,k;

clrscr();

printf(“First Name :”);

gets(fname);

printf(“Second Name :”);

gets(sname);

printf(“Last Name :”);

gets(lname);

for(i=0;fname[i]!=‘\0’;i++)

name[i]=fname[i];

name[i]=‘ ’;

for(j=0;sname[j]!=‘\0’;j++)

name[i+j+1]=sname[j];

name[i+j+1]=‘ ’;

for(k=0;lname[k]!=‘\0’;k++)

name[i+j+k+2]=lname[k];

name[i+j+k+2]=‘\0’;

printf(“\n\n”);

printf(“Complete Name After Concatenation.\n”);

printf(“%s”,name);

getche();

}

OUTPUT:

First Name : MOHAN

Second Name : KARAMCHAND

Last Name : GANDHI

Complete Name After Concatenation.

MOHAN KARMCHAND GANDHI

Explanation:

In the above program, three strings are entered. The first for loop copies string fname[] to name[] array using simple assignment. The statement following the for loop adds space after the string. The next two for loops follow the same procedure to concatenate arrays sname[] and lname[] in name[]. Thus, we get in name[] concatenation of three strings.

 

strncat() function

This function is the same as that of strcat(). The difference between them is that, the former does the concatenation of the strings with another up to the specified length. The syntax of this function is strncat (text1,text2,n); where n is the number of characters to append.

  8.28   Write a program to append the second string with specified (n) number of characters at the end of the first string using the strncat() function.

 

# include <string.h>

void main()

{

char text1[30], text2[10],n;

puts(“Enter Text1 :”);

gets(text1);

puts(“Enter Text2 :”);

gets(text2);

printf(“Enter Number of Characters to Add :”);

gets(n);

strcat(text1,“ ”);

strncat(text1,text2,n);

clrscr();

printf(“%s\n”, text1);

}

OUTPUT:

Enter Text1 : MAY I

Enter Text2 : COME IN ?

Enter Number of Characters to Add : 4

MAY I COME

Explanation:

In this program, two strings are entered. The number of characters of the second string to append in the first string is also entered. The strncat() function uses three arguments viz. Text1[], text2[] and n, where n characters of text2[] are appended in the text1[] string. In this program, two strings ‘MAY I’, ‘COME IN’ and n=4 are entered. The strncat() function returns ‘MAI I COME’.

 

strrev() function

This function simply reverses the given string. The syntax of this function is strrev(char *s);

  8.29/8.30   Write a program to display the reverse of the given string.

 

# include <string.h>

void main()

{

char text[15];

puts(“Enter String”);

gets(text);

puts(“Reverse String”);

puts(strrev(text));

}

OUTPUT:

Enter String

ABCDEFGHI

Reverse String

IHGFEDCBA

OR

 

# include <string.h>

void main()

{

char text[15];

int i=0;

clrscr();

printf(“Enter String :−”);

gets(text);

while (text[i]!= ‘\0’)

{

  printf(“\n %c is stored at location %u”,text[i],&text[i]);

  i++;

}

strrev(text);

printf(“\nReverse String :−”);

printf(“%s”,text);

i=0;

while (text[i]!= ‘\0’)

{

  printf (“\n %c is stored at location %u”,text[i],&text[i]);

  i++;

}

}

OUTPUT:

Enter String :- ABC

A is stored at location 4054

B is stored at location 4055

C is stored at location 4056

Reverse String :- CBA

C is stored at location 4054

B is stored at location 4055

A is stored at location 4056

Explanation:

In the above programs, string is entered and passed into the strrev() function. On the execution of the function, the given string appears in the reverse order. The strrev() function physically changes the sequence of characters in the reverse order. The output of the second program shows the sequence of characters and their locations.

 

strset() function

This function replaces every character of a string with the symbol given by the programmer, i.e. the elements of the strings are replaced with the arguments given by the programmer. The syntax of the function is strset(char *string,char symbol)

  8.31   Write a program to replace (set) the given string with the given symbol. Use the strset() function.

 

# include <string.h>

void main()

{

char string[15];

char symbol;

clrscr();

puts(“Enter String :”);

gets(string);

puts(“Enter Symbol for Replacement:”);

scanf(“%c”,&symbol);

printf(“Before strset() : %s\n”, string);

strset(string, symbol);

printf(“After strset() : %s\n”, string);

}

OUTPUT:

Enter String : LEARN C

Enter Symbol for Replacement: Y

Before strset() : LEARN C

After strset() : YYYYYYY

Explanation:

The strset() function requires two arguments. First one is the string and another character by which the string is to be replaced. Both these arguments are to be entered when the program executes. The strset() function replaces every character of the first string with the given character/symbol, i.e. every character of the string replaces by the entered character.

 

strnset() function

This function is the same as that of strset(). Here, the specified length is provided. The syntax of this function is strnset(char *string,char symbol,int n); where n is the number of characters to replace.

  8.32   Write a program to replace (set) the given string with the given symbol for the given number of arguments. Use the strnset() function.

 

# include <string.h>

void main()

{

char string[15];

char symbol;

int n;

clrscr();

puts(“Enter String :”);

gets(string);

puts(“Enter Symbol for Replacement:”);

scanf(“%c”,&symbol);

puts(“How many String Character to be replaced.”);

scanf(“%d”,&n);

printf(“Before strnset() : %s\n”, string);

strnset(string, symbol,n);

printf(“After strnset() : %s\n”, string);

}

OUTPUT:

Enter String : ABCDEFGHIJ

Enter Symbol for Replacement: +

How many String Characters to be replaced. 4

Before strnset() : ABCDEFGHIJ

After strnset() : ++++EFGHIJ

Explanation:

This program is the same as that of the previous one. The only difference is that instead of replacing all characters of the string, only a specified number of characters are to be replaced. Here, the number entered is 4. Hence, only the first four characters are replaced by the given symbol. The replacing process starts from the first character of the string.

 

strspn() function

This function returns the position of the string from where the source array is not matching the target one. The syntax of this function is strspn (char *string1,char *string2)

  8.33   Write a program to enter two strings. Indicate after how many characters the source string is not matching the target string.

 

# include <string.h>

void main()

{

char stra[10],strb[10];

int length;

clrscr();

printf(“First String :”);

gets(stra);

printf(“Second String :”);

gets(strb);

length=strspn(stra,strb);

printf(“After %d Characters there is no match.\n”,length);

}

OUTPUT:

First String : GOOD MORNING

Second String : GOOD BYE

After 5 Characters there is no match.

Explanation:

In this program, two strings are entered. Both the strings are passed to the function strspn(). The function searches the second string in the first string. It searches from the first character of the string. If there is a match from the beginning of the string, the function returns the number of characters that are the same.

   This function returns 0, when the second string mismatches with the first from the beginning. For example, assume the first string is ‘BOMBAY’ and the second ‘TROMBAY’. On the application of this function in the above case, the function returns 0 and message displayed will be ‘After 0 characters there is no match’.

 

strpbrk() function

This function searches the first occurrence of the character in a given string, and then it ­displays the string starting from that character. This function returns the pointer position to the first ­occurrence of the required character in text2[2]. The syntax of this function is strpbrk(char *text1,char text2);

  8.34   Write a program to print the given string from the first occurrence of the given character.

 

# include <string.h>

void main()

{

char *ptr;

char text1[20],text2[2];

clrscr();

printf(“Enter String :”);

gets(text1);

printf(“Enter Character :”);

gets(text2);

ptr=strpbrk (text1,text2[0]);

puts(“String from given Character”);

printf(ptr);

}

OUTPUT:

Enter String : INDIA IS GREAT

Enter Character : G

String from given Character : GREAT

Explanation:

In the above program, two strings and character pointer are declared. The strings are entered. Both the strings are used as arguments with the function strpbrk(). This function finds first occurrence of required character in second string and returns that address which is assigned to the character pointer *ptr. The pointer ptr displays the rest string.

Here, the first string is ‘INDIA IS GREAT’ and the second string is ‘G’. The ‘G’ occurs at the beginning of the third word. Hence, on the execution of the program the string from ‘G’ onwards is displayed. The output is only ‘GREAT’.

8.5  String Conversion Functions

Sr. No.

Function Name

Description

1

double atof(const char *s);

Converts the given string to double.

2

int atoi(const char *s);

Converts the given string to int

3

long atoi(const char *s);

Converts the given string to long.

4

double strtod(char *s,char **endptr);

Separates char and float data from the given string.

5

long strtol(char *s,char **endptr,int radix);

Separates char and long int data from the given string.

  8.35   Write a program to demonstrate the use of the atof() function.

 

# include <stdlib.h>

void main()

{

double d;

d=atof(“99.1254”);

clrscr();

printf(“%g”,d);

}

OUTPUT:

99.1254

Explanation:

In the above program, the string “99.1254” is passed as an argument to the function atof() which converts string to double. The converted number is stored in the variable d and is displayed.

  8.36   Write a program to demonstrate the use of atoi() function.

 

# include <stdlib.h>

void main()

{

int i;

i=atoi(“99.11”);

clrscr();

printf(“%d”,i);

}

OUTPUT:

99

Explanation:

The above program is the same as the last one. Here, the entered string “99.11” is converted to an integer, i.e. 99.

  8.37   Write a program to demonstrate the use of strtod().

 

# include <stdlib.h>

void main()

{

const char *string = “12.2% is rate of interest”;

char *stp;

double d;

clrscr();

d=strtod(string,&stp);

printf(“%g”,d);

printf(“\n%s”,stp);

}

OUTPUT:

12.2

% is rate of interest

Explanation:

In the above program, the string contains 12.2 a float number. The function strtod() separates float, and strings are stored in separate variables. The same is displayed.

8.6  Memory Functions

Sr. No

Function

Description

1

memcpy()

Copies n number of characters from one string to another.

2

memove()

Moves a specified range of char from one place to another.

3

memchr()

Searches for the first occurrence of the given character.

4

memcmp()

Compares the contents of the memory.

  8.38   Write a program to demonstrate the use of memcpy() function.

 

void main()

{

char *str = “Mukesh and Kamlesh”;

char stp[20];

clrscr();

memcpy(stp,str,20);

printf(“%s”,stp);

}

OUTPUT:

Mukesh and Kamlesh

Explanation:

In this program, the contents of variable str are copied to stp using the memcpy() function. The function requires three arguments, i.e. destination, source and size.

  8.39   Write a program to demonstrate the use of memmove().

 

void main()

{

char str[] = “Good Very Good”;

clrscr();

printf(“\n before : %s”,str);

memove(str,&str[5],10);

printf(“\nAfter : %s”,str);

}

OUTPUT:

before : Good Very Good

After : Very Good Good

Explanation:

In this program, the function memove() moves a specified range of char to the given location. In the output, you can observe how the strings are shifted to the beginning of the string.

  8.40   Write a program to demonstrate the use of memcmp().

 

void main()

{

char sf[]= “a”;

char ss[]= “A”;

clrscr();

printf(“%d”,memcmp(sf,ss,2));

}

OUTPUT:

32

Explanation:

In the above, two strings are compared up to the specified range. Their ASCII difference is returned.

  8.41   Write a program to demonstrate the use of memchr().

 

void main()

{

char *sf= “C IS EASY”;

clrscr();

printf(“%s”,memchr(sf,‘E’,10));

}

OUTPUT:

EASY

Explanation:

In the above program, the function memchr() searches for the first occurrence of ‘E’. After getting the desired result, the remaining string is displayed.

8.7  Applications of Strings

  8.42   Write a program to count a character that appears in a given text for a number of times. Use the while loop.

 

void main()

{

char text[20];

char find;

int i=0,count=0;

clrscr();

printf(“Type Text Below.\n”);

gets(text);

printf(“Type a character to count :”);

find=getche();

while(text[i]!=‘\0’)

{

  if(text[i]==find)

  count++;

  i++;

}

printf(“\nCharacter (%c) found in Given String = %d Times.”,find,count);

}

OUTPUT:

Type Text Below.

Programming

Type a character to count : m

Character (m) found in Given String = 2 Times.

Explanation:

In the above program, a string is entered. A single character, which is to be searched in the string, is also entered. The if condition in the while loop checks every character of the string with the single character. If there is a match counter variable ‘count’ gets incremented. After the complete execution of the while loop the counter displays the number of times the character found in the string.

  8.43   Write a program to count ‘m’ characters that appear in a given string without using any function. Use the for loop.

 

void main()

{

char text[25];

int i,count=0;

clrscr();

printf(“\nEnter the string:”);

for(i=0;i<25;++i)

{

  scanf(“%c”,&text[i]);

  if(text[i]==‘\n’)

  break;

  else

  if(text[i]==‘m’)

  ++count;

}

printf(“Character ‘m’ Found in Text=%d times.\n”,count);

getche();

}

OUTPUT:

Enter the string:

Programming is a skill.

Character ‘m’ Found in Text=2 times.

Explanation:

The logic of the program is the same as that of the previous one. Here, in this program the character that is to be searched is m which is a default character. The first if statement within the for loop terminates the loop when the user presses the ‘enter’ key. The second if statement checks every character of the entered string with m. If there is a match counter variable, count is incremented. Thus, at last count variable gives the number of times m present in the string.

  8.44   Write a program to count the following characters that appear in a string without using any functions.

 

1. ‘m’

2. ‘r’

3. ‘o’

void main()

{

char text[25]=“Programming is good habit”;

int i,m=0,o=0,r=0;

clrscr();

for(i=0;i<25;++i)

{

  if(text[i]==‘m’)

  ++m;

  if(text[i]==‘r’)

  ++r;

  if(text[i]==‘o’)

  ++o;

}

printf(“\nCharacter ‘m’ Found in Text=%d times.\n”,m);

printf(“\nCharacter ‘r’ Found in Text=%d times.\n”,r);

printf(“\nCharacter ‘o’ Found in Text=%d times.\n”,o);

getche();

}

OUTPUT:

Character ‘m’ Found in Text=2 times.

Character ‘r’ Found in Text=2 times.

Character ‘o’ Found in Text=3 times.

Explanation:

The logic of the program is the same as that of the previous one. Here, in this program the characters that are to be searched are m, r and o. The if statements within the for loops increment with respective counter variables when there is a match of these characters. Thus, after the execution of the for loop the three counter variables m, r and o are printed.

  8.45   Write a program to copy the contents of one string to another string without using the function.

 

void main()

{

char ori[20],dup[20];

int i;

clrscr();

printf(“Enter Your Name :”);

gets(ori);

for(i=0;ori[i]!=‘\0’;i++)

dup[i]=ori[i];

dup[i]=‘\0’;

printf(“Origional String : %s”,ori);

printf(“\nDuplicate String : %s”,dup);

}

OUTPUT:

Enter Your Name : SACHIN

Original String : SACHIN

Duplicate String : SACHIN

Explanation:

In the above program, two character arrays are declared. The source string is entered. Using the for loop and assignment operator each character of the source array (ori[]) is assigned to the target array dup[]. After the execution of the for loop, NULL character is appended in the target string to mark the end of the string. Using the printf() function both the strings are displayed.

  8.46   Write a program to know whether the entered character string is palindrome or not. (Palindrome word reads the same from left to right and right to left.)

(Ex. DAD, ABBA, MUM)

 

# include <string.h>

# include <process.h>

void main()

{

char str[10];

int i=0,j,test;

clrscr();

printf(“Enter the word :”);

scanf(“%s”,str);

j=strlen(str)−1;

while(i<=j)

{

  if (str[i]==str[j])

  test=1;

  else

  {

    test=0;

    break;

  }

  i++;

  j−−;

}

if(test==1)

printf(“Word is palindrome.\n”);

else

printf(“\n Word is not Palindrome.\n”);

}

OUTPUT:

Enter the word : ABBA

Word is palindrome.

Explanation:

In the above program, a string is entered that is to be tested for ‘palindrome’. The string length is calculated and assigned to variable ‘j’. The value of ‘j’ is less by one with the original string length because the array elements are counted from zero (0).

The if statement within the while loop checks the first and last characters of the string for equality. Counter variables ‘i’ and ‘j’ denote the first and last characters, respectively. To get the successive characters from both the ends, variable ‘i’ is incremented and ‘j’ is decremented. Till there is a match variable ‘test’ is 1 and the loop continues, otherwise test is set to zero (0) and the break statement terminates the loop.

  8.47   Write a program to compare the strings using the strcmp() function and display their ASCII difference. Initialize the strings and copy some names of the cities to the variables.

 

# include <string.h>

void main()

{

char a1[15],a2[15],a3[15],a4[15],a5[15],a6[15];

int c1,c2,c3;

strcpy(a1,“NAGPUR”);

strcpy(a2,“NAGPUR”);

strcpy(a3,“PANDHARPUR”);

strcpy(a4,“KOLHAPUR”);

strcpy(a5,“AURANGABAD”);

strcpy(a6,“HYDERABAD”);

clrscr();

c1=strcmp(a1,a2);

c2=strcmp(a3,a4);

c3=strcmp(a5,a6);

printf(“\nAscii Difference between two strings\n”);

printf(“Difference between (%s %s)=%d\n”,a1,a2,c1);

printf(“Difference between (%s %s)=%d\n”,a3,a4,c2);

printf(“Difference between (%s %s)=%d\n”,a5,a6,c3);

getche();

}

OUTPUT:

Difference between (NAGPUR NAGPUR)= 0

Difference between (PANDHARPUR KOLHAPUR)= 5

Difference between (AURANGABAD HYDERABAD)=−7

Explanation:

In the above program, five character arrays are declared. Using the strcpy() function the names of cities are copied to arrays. Using the strcmp() function, strings are compared. The strcmp() returns the ASCII difference of two strings. The ASCII values of the first characters of two strings are taken into account for comparison. Rest of the elements are not considered for ASCII difference. The ASCII value of the first character of the first string is subtracted from the ASCII value of the first character of second string. Table 8.4 illustrates the calculation.

Table 8.4 ASCII difference

ASCII Value

ASCII Value

Difference

78 (N)

78 (N)

0

80 (P)

75 (K)

5

65 (A)

72 (H)

−7

  8.48/8.49   Write a program to enter names of cities and display all the entered names alphabetically.

 

void main()

{

char city[5][20];

int i,j;

clrscr();

printf(“Enter Names of Cities.\n\n”);

for(i=0;i<5;i++)

scanf(“%s”,city[i]);

printf(“Sorted List of Cities.\n\n”);

for(i=65;i<=122;i++)

{

  for(j=0;j<5;j++)

  {

    if(city[j][0]==i)

    printf(“\n%s”,city[j]);

  }

}

}

OUTPUT:

Enter Names of Cities.

MUMBAI

NANDED

BANGLORE

KANPUR

INDORE

Sorted List of cities.

BANGLORE

INDORE

KANPUR

MUMBAI

NANDED

Explanation:

In the above program, the first for loop is used for entering the names of cities. The city name can be entered in either upper or lowercase. Hence, the second for loop is initialized from 65 to 122 where 65 is the ASCII value of ‘A’ and 122 ASCII value of ‘z’. The if statement within the third for loop makes the comparison. If there is a match, the city name will be displayed, otherwise the loop continues. Thus, the elements of city[][] array are displayed in a sorted order.

 

OR

 

# include <string.h>

void main()

{

char city[5][20],temp[20];

int i,j;

clrscr();

printf(“Enter Names of Cities\n”);

for(i=0;i<5;i++)

scanf(“%s”,city[i]);

printf(“\nSorted List of Cities”);

for(i=1;i<5;i++)

{

  for(j=1;j<5;j++)

  {

    if(strcmp(city[j−1],city[j])>0)

    {

      strcpy(temp,city[j−1]);

      strcpy(city[j−1],city[j]);

      strcpy(city[j],temp);

    }

  }

}

for(i=0;i<5;i++)

printf(“\n%s”,city[i]);

}

OUTPUT:

Enter Names of Cities.

MUMBAI

NANDED

BANGLORE

KANPUR

INDORE

Sorted List of Cities.

BANGLORE

INDORE

KANPUR

MUMBAI

NANDED

Explanation:

In the above program, standard string functions strcmp() and strcpy() are used. The strcmp() function compares two successive city names. If theirASCII difference is greater than zero, city names are exchanged. This is accomplished by the body of the if statement. Thus, on the execution of the program cities are displayed in the alphabetical order.

  8.50/8.51   Write a program to find the number of words in a given statement. Exclude spaces between them.

 

void main()

{

char text[30];

int count=0,i=0;

clrscr();

printf(“Enter The Line of Text \n”);

printf(“Give One Space After Each word\n”);

gets(text);

while(text[i++]!= ‘\0’)

if(text[i]==32 || text[i]== ‘\0’)

count++;

printf(“The Number of words in line = %d\n”,count);

}

OUTPUT:

Enter The Line of Text

Give One Space After Each word

Read Books

The Number of words in line = 2

Explanation:

In the above program, a string is entered. sIt is known that the single space separates two consecutive words. The logic for finding the number of words in a statement is to detect the number of spaces and NULL characters. For example, in a statement ‘C IS A PROGRAMMING LANGUAGE’ there are four spaces and a NULL character when the string is terminated. Thus, the total characters are five (4+1). The if statement counts the number of spaces and NULL characters in the string.

 

OR

 

void main()

{

char text[30];

int count=0,i=0;

clrscr();

printf(“Enter Text Below :”);

gets(text);

while(text[i]!=‘\0’)

{

  if(((text[i]>=97) && (text[i]<=122)) || ((text[i]>=65) && (text[i]<=90)))

  {

    i++;

    if(text[i]==32)

    {

      count++;

      i++;

    }

  }

}

if(text[i]==‘\0’)

count++;

printf(“The Number of words in line = %d\n”,count);

}

OUTPUT:

Enter Text Below : Reading is a good Habit

The Number of words in line = 5

Explanation:

In the above program, a string is entered. The first if statement within the while loop checks every element of string whether it is a character or space. If it is a character variable ‘i’ is incremented and checked with second if statement. If it is space then countervariables ‘i’ and ‘count’ are incremented. Thus, by counting spaces and NULL characters the total number of words is calculated.

  8.52   Read the names of mobile customers through keyboard and sort them alphabetically on the last name. Display the sorted list on the monitor.

 

# include <string.h>

void main()

{

char fname[20][10],sname[20][10],surname[20][10];

char name[20][20],mobile[20][10],temp[20];

int i,j;

clrscr();

printf(“Enter Names and Mobile Numbers.\n”);

for(i=0;i<5;i++)

{

  scanf(“%s %s %s %s”,fname[i],sname[i],surname[i],mobile[i]);

  strcpy(name[i],surname[i]);

  strcat(name[i],“,”);

  temp[0]=fname[i][0];

  temp[1]=‘\0’;

  strcat(name[i],temp);

  strcat(name[i],“.”);

  temp[0]=sname[i][10];

  temp[1]=‘\0’;

  strcat(name[i],temp);

}

for(i=1;i<=5−1;i++)

for (j=1;j<=5−i;j++)

if(strcmp(name[j−1],name[j])>0)

{

  strcpy(temp,name[j−1]);

  strcpy(name[j−1],name[j]);

  strcpy(name[j],temp);

  strcpy(temp,mobile[j−1]);

  strcpy(mobile[j−1],mobile[j]);

}

strcpy(mobile[j],temp);

printf(“List of Customers in alphabetical Order.”);

for(i=0;i<5;i++)

printf(“\n%−20s\t %−10s\n”,name[i],mobile[i]);

}

OUTPUT:

Enter Names and Mobile Numbers.

K S MORE   458454

J M CHATE  658963

M M GORE   660585

L K JAIN   547855

J J JOSHI  354258

List of Customers in alphabetical Order.

CHATE J.M. 658963

GORE M M   660585

JAIN L K   547855

JOSHI J J  354258

MORE K S   458454

Explanation:

The logic used here is the same as logic used in the program where city names are sorted alphabetically.

Summary

This chapter is focused on strings. In this chapter, you have learnt how to declare and initialize strings. It is also very important to identify the end of the string. This is followed by NULL (\0) character. The various formats for display of the strings are demonstrated with numerous examples.

String handling has strong impact in our life string problems such as conversion of lower to uppercase, reversing, concatenation, comparing, searching and replacing of string elements. It is also discussed how to perform these activities with and without standard library functions.

Memory functions have also been illustrated together with programming examples.

After having performed programs discussed in this chapter, the programmer should not face any problem in solving string-handling applications.

EXERCISES

I  Fill in the blanks:

  1. The ______ is a group of characters, digits and symbols.
    1. number
    2. array
    3. string
  2. The string is terminated with ______ character.
    1. ‘?’
    2. ‘\0’
    3. ‘#’
  3. Consider the declaration char name[10];. Out of following, ______cannot be held in name?
    1. “A12BC34D”
    2. “hello”
    3. “1a3b5c7d9e”
  4. _____ is not the library string function.
    1. strlen()
    2. strrev()
    3. strstrstr()
  5. ______ copies one string to another.
    1. strstr()
    2. strcpy()
    3. strcat()
  6. The length of string name in the following program segment is _____.

    char[]name ={‘h’,‘e’,‘l’,‘l’,‘o’,‘\0’};

    printf(“%d”,strlen(name));

    1. 5
    2. 6
    3. 7
  7. The printf statement in the following program segment prints _____.

    char name[] = “AbCdEf”;

    printf(“%s”,strlen(strlwr(strupr (name))));

    1. AbCdEf
    2. ABCDEF
    3. Abcdef
    4. none of the above three
  8. _____ header file is to be included for using string functions.
    1. str.h
    2. string.h
    3. stdio.h
  9. The printf() statement in the following program statement prints _____.

    char name[] = “India”;

    char *a;

    a = name;

    printf(“%s”,a);

    1. India
    2. I
    3. no output
  10. Keyword const can be used with ______.
    1. string
    2. pointer
    3. both string and pointer
  11. The free() frees blocks allocated with ______.
    1. malloc()
    2. gets()
    3. stralloc()
  12. ________ is used to allocate main memory.
    1. gets()
    2. malloc()
    3. stralloc()
  13. ________ is used for duplication of a string.
    1. gets()
    2. strdup()
    3. strcmp()
  14. ________ appends source to destination string.
    1. strcat()
    2. strdup()
    3. strcmp()

II  True or false:

  1. Array of characters is also known as a string.
  2. The name of array is the pointer to the first element of the array.
  3. strcat() function is used to find the length of the string.
  4. In const char* p = “Hello” pointer is fixed and string is constant.
  5. The array of pointers, declared as char *a[], is a 2D character array.
  6. In any array, its ith element can be accessed using the - arr[i], i[arr], *(i+arr) and *(arr+i).
  7. Function malloc() can be used to allocate space in memory at compile time.
  8. In multidimensional array the consecutive arrays are not stored in contiguous memory locations.
  9. If you want to take the address of a person as an input, you will mostly prefer scanf().
  10. The efficient declaration in terms of memory for multidimensional string is *mul[] than mul[20][30].
  11. The string is declared with int name[];
  12. “1ABCDE2345” is a valid string.
  13. “$ABCDE4567” is an invalid string.
  14. NULL character appears at first if the string is reversed
  15. strlen() counts the number of characters including \0 (null).
  16. strcmp() compares two arrays elements by elements
  17. ‘ABCD’ is a valid string.
  18. strcpy() copies string from the destination to source string.

III  Match the functions/words given in Group A with meanings in Group “B”:



IV  Selecting the appropriate option from the multiple choices given below:

  1. The string always ends with
    1. ‘\0’ character
    2. ‘\’ character
    3. ‘0\’ character
    4. None of the above
  2. What will be the output of the program

    void main()

    {

    char nm[]={‘A’,‘N’,‘S’,‘I’,0,‘C’,‘\0’};

    int x=0;

    clrscr();

    while (nm[x]!=‘\0’)

    printf (“%c”,nm[x++]);

    }

    1. ANSI
    2. ANSI0C
    3. ANSIC
    4. None of the above
  3. What will be the size of character array

    void main()

    {

    char x[]={‘s’,‘a’,‘\0’};

    printf (“\n %d”,sizeof(x));

    }

    1. 3
    2. 2
    3. 0
    4. None of the above
  4. What will be the output of the following program?

    # include <string.h>

    void main()

    {

    char x[]=“a1b2c3d4e5f6g7h8i9j0”;

    int t=0;

    clrscr();

    for(t=1;x[t]!=0 && t<=strlen(x);t+=2)

    printf (“%c”,x[t]);

    }

    1. 1234567890
    2. abcdefghij
    3. a1b2c3d4e5f6g7h8i9j0
    4. None of the above
  5. What will be the output of the following program?

    void main()

    {

    char txt[]=“12345\0abcdef”;

    clrscr();

    printf(“%s”,txt);

    }

    1. 12345
    2. abcdef
    3. 12345\0abcdef
    4. None of the above
  6. What will be the output of the following program?

    void main()

    {

    char txt[]=“ABCDEF\0GHIJKL”;

    clrscr();

    printf(“%s %d”,txt,sizeof

    (txt));

    }

    1. ABCDEF 14
    2. ABCDEF\0GHIJKL 14
    3. ABCDEF 7
    4. None of the above

V  Attempt the following programming exercises:

  1. Write a program to arrange a set of fruit names given below in descending order (reverse alphabetic). (mango, banana, apple, orange, graphs, coconut, water melon and papaya).
  2. Write a program to arrange the following names in the alphabetic order. The sorting is to be done on the first three characters of the first name.

    (Ashok, Alok, Akash, Amit, Amol, Anil, Ashish and Anand).

  3. Write a program to enter some text and display the text in reverse order. (Example: ‘I am happy’ will be displayed as ‘happy am I’).
  4. Write a program to enter five full names of persons. Display their names, initials and last names.
  5. Write a program to enter text through keyboard. Convert first character of each word in capital and display the text.
  6. Write a program to enter some text through the keyboard. Insert dot (.) after every three words in the text. The first character after every dot should be converted to capital.
  7. Write a program to enter some te xt through the keyboard. Count the number of words that starts from ‘w’. Display such words and count them.
  8. Write a program to print the entered word with all possible combinations.
  9. Write a program to encrypt the te xt ‘INDIA’. The output should be ‘KPFKC’. (‘A’ is to be replaced with ‘C’, ‘B’ with ‘D’ and ‘C’ with ‘E’ and so on.)
  10. Write a program to dycrypt the text ‘KPFKC’ to get original string ‘INDIA’.

VI  Answer the following questions:

  1. What are strings? How are they declared?
  2. What is the NULL character? Why is it important?
  3. Is it possible to initialize the NULL character in the string?
  4. Why is it necessary to count NULL characters while declaring string?
  5. What is the difference between the functions strcmp() and stricmp()?
  6. What is the use of strrev() and strlen() functions?
  7. What is the use of strcpy() and strdup() functions?
  8. What is the difference between strcpy() and strncpy() functions?
  9. What is the difference between NULL, ‘\0’ and 0?
  10. Describe any of the memory functions.
  11. Describe any three string conversion functions.
  12. What is the use of atof() function?

VII  What will be the output/s of the following program/s?


  1. # include <string.h>

    void main()

    {

    char *a1[12]={“MAHARASHTRA”};

    clrscr();

    printf(“%s”,*a1);

    getche();

    }


  2. # include <string.h>

    void main()

    {

    char a1[12]=“MAHARASHTRA”;

    char *a2[13]={“MADHYAPRADESH”};

    clrscr();

    printf(“%s”, a1);

    printf(“%s”,*a2);

    getche();

    }


  3. Program to find the length of the string.

    void main()

    {

    char text[20];

    int len;

    clrscr();

    printf(“type text below.\n”);

    gets(text);

    len=strlen(text);

    printf(“lenth of the strng

    is=%d”,len);

    }


  4. Program to copy the string using strcpy function

    void main()

    {

    char name1[10]={‘P’,‘r’,‘i’,‘y’,‘a’},name2[10];

    clrscr();

    printf(“\n Original name=%s”,name1);

    strcpy(name2,name1);

    printf(“\n Copied name is=%s”,name2);

    getch();

    }


  5. Without strcpy

    void main()

    {

    char main[10]=“abcd”,dup[10];

    int i;

    clrscr();

    for(i=0;i<10;i++)

    dup[i]=main[i];

    printf (“Origional String : %s”,main);

    printf(“\nDuplicate String : %s”,dup);

    getche();

    }



  6. void main()

    {

    char group[15]={‘I’,‘n’,‘d’,‘i’,‘a’};

    int len=0,i;

    clrscr();

    for(i=0;group[i]!=‘\0’;i++)

    len++;

    printf(“Length of the string is=%d”,len);

    getch();

    }


  7. Program on comparison of two strings

    void main()

    {

    char str1[20]={‘C’,‘o’,‘m’,‘p’,‘u’,‘t’,‘e’,‘r’},

    str2[20]={‘C’,‘o’,‘m’,‘p’,‘u’,‘t’,‘e’,‘r’};

    clrscr();

    if( (strcmp(str1,str2))==0)

    printf(“Length of the strings are same \n”);

    else

    printf(“Length of the strings are not same \n”);

    getch();

    }

VIII  Find the bug/s in the following programs:


  1. # include <string.h>

    void main()

    {

    char a1[]={“KOLKATA”};

    int i;

    clrscr();

    while(a1[i++]!=‘\0’)

    printf(“%c”,a1[i]);

    getche();

    }


  2. # include <string.h>

    void main()

    {

    char a1[6]={‘NAGPUR’};

    clrscr();

    printf(“%c”,a1);

    getche();

    }


  3. # include <string.h>

    void main()

    {

    char *a[]=“ROYAL”;

    clrscr();

    printf(“%s %u”,*(a),&*a);

    getche();

    }


  4. # include <string.h>

    void main()

    {

    char a1[6]={“CHENNAI”};

    int i;

    clrscr();

    for(i=0;i<7;i++)

    printf(“%c”,a1[i]);

    ++i;

    getche();

    }


  5. void main()

    {

    char text[15]=“MOUNTAIN”;

    int i;

    clrscr();

    for(i=7;i>=0;i−−)

    printf(“%.8d”,text[i]);

    getche();

    }


  6. # include <string.h>

    void main()

    {

    char *a2[10]={“MADHYAPRADESH”};

    clrscr();

    printf(“%s”,*&(a2));

    getche();

    }


  7. void main()

    {

    char str1[15]=‘snowy’,

    str2[15]=‘sunny’;

    clrscr();

    printf(“\n Source String-:%s”, str1);

    printf(“\n Destination String-:%s”,str2);

    strncpy(str2,str1,3);

    printf(“\nDestination String-:%s”,str2);

    getche();

    }

ANSWERS

I  Fill in the blanks:

Q.

Ans.

1.

c. String
It is a group of characters, digits and symbols. Actually it is an array of characters. So, more specific answer is String.

2.

b. ‘\0’
Every string in C is terminated with ‘\0’ (NULL) character.

3.

c. 1a3b5c7d9e
In C the maximum characters that can fit into a string is less than its size by 1. Because, the string always terminates with ‘\0’ (NULL) character.

4.

c. strstrstr()
There is no function strtstrstr() in C.

5.

b. strcpy()
strcpy() function is used to copy a string from source to destination string.

6.

a. 5
In C the string i.e. character array is terminated by ‘\0’ (NULL) character. If the ‘\0’ is specified like in declaration the compiler doesn’t insert more ‘\0’. Also, the strlen() function gives the length of string without ‘\0’ character.

7.

d. None of the above three
Understand the sequence of functions. The outer function executes last. So we are trying to print integer with %s. It’ll print something which we cannot predict.

8.

b. string.h
In C the string.h header file contains the functions needed by the strings.

9.

a. India
In character array the name of the array is same as the pointer to the first ­element.

10.

c. both string and pointer

11.

a. malloc()

12.

b. malloc()

13.

b. strdup()

14.

a. strcat()

II  True or False:

Q.

Ans.

1.

T

2.

T

3.

F

4.

F

5.

T

6.

T

7.

F

8.

F

9.

F

10.

T

11.

F

12.

T

13.

F

14.

F

15.

F

16.

T

17.

F

18.

F.

III  Match the functions/words given in Group A with meanings in Group “B”:


  1. Q.

    Ans.

    1.

    F

    2.

    E

    3.

    D

    4.

    C

    5.

    B

    6.

    A

  2. Q.

    Ans.

    1.

    C

    2.

    B

    3.

    A

    4.

    D

IV  Selecting the appropriate option from the multiple choices given below:

Q.

Ans.

1.

a

2.

a

3.

a

4.

a

5.

a

6.

a

VII  What will be the output/s of the following program/s?

Q.

Ans.

1.

MAHARASHTRA

2.

MAHARASHTRA MADHYAPRADESH

3.

My name is=Romali
Length of the string is=6

4.

Original name=Priya
Copied name is=Priya

5.

Origional String : abcd
Duplicate String : abcd

6.

Length of the string is=5

7.

Length of the strings are same

VIII  Find the bug/s in the following programs:

Q.

Ans.

1.

i’is to be initialized with some value say i=−1.

2.

Array initialization is incorrect and %s is to used instead of %c.

3.

ROYAL must be enclosed with double quote.

4.

char array is to be initialized with 7 instead of 6.

5.

Replace c instead of d in printf statement.

6.

&’ operator to be deleted.

7.

Double quotation mark is needed in char statement.