C-Programming

String

Introduction to the string:

We can use simple variable to store the numeric values but if we have to store a word then what would we do? The answer to this question is we have to use the concept of string. String is the word or groups of word. Since word contains the set of character then naturally the string also contains the set of character. Therefore we can define the string as a set of character data or array of character type. Here in the case of string there is not only one character but the set of character therefore in the case of string manipulation we should use array as the fundamental thing. If we have to store only one string then we can use single dimensional array of character type as:

char string_name[number of character in the string];

For example: char name[10];

The example tells the computer that name is the array of character type that can store maximum 10 characters. Here character means not only the alphabets, but also digits, white spaces, underscore, comma, other special characters etc.

If we have to store more than one sting then we have to use concept of two dimensional arrays which takes the form as:

char string_name[no. of string][no. of character that each string can hold];

For example: char name[10][15];

This example tells the computer that name is an array of character type that cans store10 strings having maximum number of character 15. 

 

How to assign the value of a string:

Here value of string does not mean the numeric value but set of character. In the case of numeric variable we can assign the value by writing the statement just:

variable=value;

  1. a=10;

But in the case of string we can not use this syntax. To assign a string in the string variable we have to use one string function strcpy( ) which copies the string to the variable and this takes the form as:

strcpy(variable, “string”);

For example:

strcpy(name,”ramkrishna”);

This statement assigns the string ramkrishna in the string variable name.

How to display the content of string variable?

We can display the content of a string variable as in the case of other simple variable which takes the form:

printf(“format_specifier”,argument);

In the case of string the format specifier is %s.

Eg. printf(“%s”,name);

For the purpose of displaying the content of the string variable, we also have a special string function puts( ); which takes the form as:

puts(string_variable);

This function doesn’t require any format specifier because this function is only for the string therefore computer automatically understood the string.

Eg. puts(name);

How to use this function puts() to display the text?

To display the text it takes the similar syntax as that takes the printf ( ) function. The syntax is:

puts(“text”);

  1. puts(“we are studying string.”);

Write a program that assigns the name Tol Man Shrestha in the string variable and display the value of that variable.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char name[15];

clrscr();

strcpy(name,”Tol Man Shrestha”);

printf(“%s”,name);      //OR we can use puts(name);

getch();

}

 

How to read the string variable from the key board?

We can read the string in the similar way as in the case of simple variable by using scanf() function which takes the form:

scanf(“format_specifier”,argument);

  1. scanf(“%s”,name);

One limitation of this function is that it can not read or store the data after it has encountered the white space. Therefore we can not read the string Ram Prasad at a time using the function scanf(); although there is enough spaces to store the data. To overcome this limitation there is another string function gets();used to read the string which can read white spaces also and this takes the form as:

gets(string_variable);

  1. gets(name);

 

Write a program in C that reads a name from the key board and displays on the screen.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char name[20];

clrscr();

printf(“Please enter a name:  \t”);

gets(name);

printf(“\n\nthe entered name is %s.”,name);

getch();

}

sample output of the program:

Please enter a name:       Durga Narayan Shrestha

the entered name is Durga Narayan Shrestha._

 

Write a program that read 10 student’s name and displays these name.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char name[10][20];

int i;

clrscr();

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

      {

printf(“\nPlease enter the %dth name:\t”,i);

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

      }

printf(“\n\nThe entered names are:\n”);

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

printf(“\n%d. %s”,i,name[i]);

 getch();

}

 

sample output:

 

Please enter the 1th name:      Archana

Please enter the 2th name:      Tolman

Please enter the 3th name:      Manju

Please enter the 4th name:      Shusma

Please enter the 5th name:      Sanjina

Please enter the 6th name:      Pradip

Please enter the 7th name:      Tara

Please enter the 8th name:      Gyanu

Please enter the 9th name:      Krishna

Please enter the 10th name:     Ramchandra

The entered names are:

  1. Archana
  2. Tolman
  3. Manju
  4. Shusma
  5. Sanjina
  6. Pradip
  7. Tara
  8. Gyanu
  9. Krishna

10.Ramchandra

 

 

Other string manipulation functions:

Those library functions which are used in the manipulation of the strings are called string functions. We have studied some string functions such as gets( ), puts( ),strcpy( ). There are also some other string functions whose header file is string.h and they are:

  • strlen()
  • strrev()
  • strcmp()
  • strcpy()
  • strlwr()
  • strupr()
  • strcat()
  1. The function strlen(); :

This function stands for string length. Therefore this function is used to determine the length of the string. Here length of the string means the number of characters that is holding the variable. It returns the number of characters present in the string except for the null character ‘\0’. This function takes the form as:

strlen(string_variable);

Eg. Write a program that read a string from the user and display the number of character present in it.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

int length;

char string[25];

printf(“\nPlease enter a string:\t”);

gets(string);

length=strlen(string);

printf(“\n\nThere are %d letters in the entered string.”);

getch();

}

Sample output of the program:

Please enter a string:     Nawalparasi

There are 11 letters in the entered string.

 

  1. The strrev() function:

This function is used to reverse a string directly except the terminating null character ‘\0’. The syntax of the function is:

strrev(string_variable);

  1. Write a program to illustrate the function of strrev();.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char string[20];

printf(“\nPlease enter a string:\t”);

gets(string);

printf(“\nBefore reversing the string, the entered string was %s.”,string);

strrev(string);

printf(“\nAfter reversing the string, the entered string is %s.”,string);

getch();

}

Sample output of the program:

Please enter a string:  Bishnu Bhakta Baral

Before reversing the string, the entered string was Bishnu Bhakta Baral.

After reversing the string, the entered string is laraB atkahB unhsiB.

  1. The function strcmp():

This function stands for string compare. Therefore this function is used to compare two strings. Simply comparing two variable means subtracting second variable from first one. In the case of string the comparison begins from the first character of each string variable and continues with the subsequent until the end of the strings is reached or the corresponding character is differ. This function also returns the integer value, either positive or negative or zero.  The general syntax of this function is:

strcmp(string1,string2);

If string1 and string2 are two strings then on comparing these strings

  • strcmp( ) returns +ve value i.e greater than 0 only if string1 is greater than string2.
  • strcmp( ) returns -ve value i.e less than 0 only if string1 is less than string2.
  • strcmp( ) returns zero value i.e equal to 0 only if string1 is equal to string2

It should be noted that the string function strcmp() does not compares the length of the strings. This function compares two strings treating both upper and lowercase letter equally.

  1. The function strcpy():

We can also copy the content of one string variable to another string variable as in the case of simple variable by using the string function strcpy( ) which stands for string copy. To copy the content of one variable on another, this takes the form as:

strcpy(string2,string1);

This statement copies the content of the string1 into the string2.

  1. The function strlupr() and strupr():

These two functions are stand for string in uppercase and string in lowercase respectively. Therefore the function strupr() is used to change the whole string in upper case and strlwr( ) is used to change the whole string in lower case.

Syntax:

strupr(string);

strlwr(string);

  1. Write a program that reads a name of a student and converts it in lower case and upper case.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char name[25];

clrscr();

printf(“Please enter the name :\t”);

gets(name);

strupr(name);

printf(“\nThe name of the student in upper case is %s.”,name);

strlwr(name);

printf(“\nThe name of the student in lower case is %s.”,name);

getch();

}

Sample output of the program:

Please enter the name : Tara Devi Shrestha

The name of the student in upper case is TARA DEVI SHRESTHA.

The name of the student in lower case is tara devi shrestha.

  1. The function strcat( ):

The function strcat() stands for string concatenation. Therefore this function is used to concatenate the two strings. The concatenate means add the strings. The syntax of this function is:

strcat(string1,string2);

  1. Write a program that joins two different strings and assign in another string variable and display this string variable.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char str1[15],str2[10],str3[25];

clrscr();

printf(“Please enter the first string/word:\t”);

scanf(“%s”,str1);

printf(“Please enter the second string/word:\t”);

scanf(“%s”,str2);

strcpy(str3,strcat(str1,str2));

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

getch();

}

Sample output of the program:

Please enter the first string/word:    WesternRegion

Please enter the second string/word:   Campus

WesternRegionCampus

String as the set of character/ Character manipulation:

Since string is the set of characters, therefore we can tread the string as an array of character and can be manipulate as characters without using any string functions. In stead of using string function we can also use the character functions such as getchar( ) and putchar( ). We have already familiar with these two functions. There are also other character functions some of them are as follows:

  1. toupper( )
  2. tolower( )
  • isalpha( )
  1. isdigit( )
  2. isspace( )
  3. ispunct( )
  • isalnum( )
  • iscntrl( )
  1. islower( )
  2. isupper( )
  3. isprint ( )
  • toascii( )

 

  1. The functions toupper( ) and tolower( ):

As in the case of string struper( ) and strlwr( ) is used to convert the whole string in uppercase or lowercase, in the same way in the character manipulation toupper( ) and tolower( ) are used to convert the character in uppercase and lowercase respectively. The syntaxes of these functions are:

toupper(character_variable);

tolower(character_variable);

  1. Write a program that takes a string and displays the string in upper case and lower case without using any string functions.

#include<stdio.h>

#include<conio.h>

void main()

{

char string[50];

int i;

clrscr();

printf("\nPlease enter a string:\t");

for(i=0;(string[i]=getchar())!='\n';i++);

printf("\n\n The entered string is :\n");

for(i=0;string[i]!='\n';i++)

printf("%c",string[i]);

printf("\n\nThe string in upper case is:\n");

for(i=0;string[i]!='\n';i++)

    {

    string[i]=toupper(string[i]);

    printf("%c",string[i]);

    }

printf("\n\nThe string in lower case is:\n");

for(i=0;string[i]!='\n';i++)

    {

    string[i]=tolower(string[i]);

    printf("%c",string[i]);

    }

getch();

}

Sample output of the program:

Please enter a string:  Hello, I am from Nawalparasi.

 The entered string is :

Hello, I am from Nawalparasi.

The string in upper case is:

HELLO, I AM FROM NAWALPARASI.

The string in lower case is:

hello, i am from nawalparasi.

  1. The functions isalpha( ) and isdigit( ):

                               By the name of these functions we can guess what they do. Yes, they are used to determine whether the character is alphabet or digit respectively. The character will be alphabet if the character is from ‘a’ to ‘z’ or from ‘A’ to ‘Z’ and will be digit if it falls under the range ‘0’ to ‘9’.

The prototype for these functions is ctype.h.

The syntax of the functions is:

isalpha(character_variable);

isdigit(character_variable);

Write a program that determines whether the entered character is alphabet or digit or any other character.

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

void main()

{

char ch;

printf(“\nPlease enter a character:\t”);

ch=getchar();  //ch=getche(); OR scanf(“%c”,&ch);

if(isalpha(ch))

printf(“\n%c is an alphabet.”,ch);

else if(isdigit(ch))

printf(“\n%c is a digit.”,ch);

else

printf(“\n%c is neither an alphabet nor a digit.”,ch);

getch();

}

sample output of the program:

Please enter a character:       D

D is an alphabet.

Please enter a character:       2

2 is a digit.

Please enter a character:       %

% is neither an alphabet nor a digit.

  1. The functions isspace( ) and ispunct( ):

These functions are used to determine whether the given character is space and punctual character such as comma, full stop, question mark etc. The prototype of these functions is also ctype.h. The syntaxes of these functions are:

      isspace(character);

ispunct(character);

  1. The functiosns isalnum( ) and iscntrl( ) :

These functions are used to check whether the character is alphanumeric (i.e, either alphabet or digit), or whether the character is control character. All of these functions return either 1 or 0. The syntax of these functions is similar to other character manipulation functions.

            isalnum(character);

     iscntrl(character);

                                   

  1. The functions islower( ) and isupper(  ):

            These functions are used to check whether the given character is lowercase character or uppercase character. The prototype of these functions is also ctype.h . The syntaxes of these functions are:

                                islower(character);

             isupper(character);

  1. The functions isprint() and toascii( ):

                      The function isprint( ) is used to check whether the given character is printable or not and the function toascii( ) is used to convert the character into the ascii value. The header file for these functions is ctype.h. The function isprint( ) returns either 1 or 0 where as the function toascii( ) always returns an integer value. The syntaxes of these functions are as follow:

                      isprint(character);

           toascii(character);

Write a program that takes a string from the user and displays the ASCII code of all the characters of the string.

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

void main()

{

char string[50];

int i,asci;

clrscr();

printf("\nPlease enter a string:\n\n");

for(i=0;(string[i]=getchar())!='\n';i++); 

printf("\nCharacters\t\tAscii value\n");

for(i=0;string[i]!='\n';i++)

{

asci=toascii(string[i]);

printf("\n%c\t:\t%d",string[i],asci);

}

getch();

}

Sample output of the program:

 

Please enter a string:

 

I am studying in B.E.

 

Characters      Ascii value

 

I       :       73

        :       32      (blank space)

a       :       97

m       :       109

        :       32      (blank space)

s       :       115

t       :       116

u       :       117

d       :       100

y       :       121

i       :       105

n       :       110

g       :       103

        :       32      (blank space)

i       :       105

n       :       110

        :       32

B       :       66

.       :       46

E       :       69

.       :       46

 

      /*a program which read a line of text and count the no. of vowels,consonants,digits,extra character. */

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<ctype.h>

void main()

   {

   int i,j,n,v=0,c=0,d=0,s=0,ec=0,p=0,up=0,lo=0;

   char lin[500];

   clrscr();

   printf("Write a line:\n");

   for(i=0;((lin[i]=getchar())!='\n');i++);

   for(i=strlen(lin)-1;i>=0;i--)

     {

     if(isalpha(lin[i]))

          {

        if(lin[i]=='a'||lin[i]=='e'||lin[i]=='i'||lin[i]=='o'||lin[i]=='u'||lin[i]=='A'||lin[i]=='E'||lin[i]=='I'||lin[i]=='O'||lin[i]=='U')

          v++;

          else

          c++;

          if(isupper(lin[i]))

          up++;

          else

          lo++;

          }

     if(isdigit(lin[i]))

     d++;

     if(isspace(lin[i]))

     s++;

     if(ispunct(lin[i]))

     p++;

      if(isalpha(lin[i])|isdigit(lin[i])||isspace(lin[i])||ispunct(lin[i]))

     continue;

     else

     ec++;

     }

   printf("\n\n\n\nTotal no. of character:\t%d",strlen(lin));

   printf("\nNo. of vowels:\t%d",v);

   printf("\nNo. of consotants:\t%d",c);

   printf("\nNo. of digits:\t%d",d);

   printf("\nNo. of white space (including enter):\t%d",s);

   printf("\nNo. of punctual character:%d",p);

   printf("\nNo. of upper case character:\t%d",up);

   printf("\nNo. of lower case character:\t%d",lo);

   printf("\nNo. of extra character:   %d",ec);}

Pointers (Prev Lesson)
(Next Lesson) Important Questions from Strings
Back to C-Programming

No Comments

Post a Reply

Teacher
Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!