Wednesday, 8 January 2014

C Programming Language Tutorial XIII – Character Array



String (character array)
 -   A set of characters known as character array.
-   A string is a one dimensional character array that gets terminated with a special character ‘\0’.
-   ‘\0’ is called as null character.
e.g. – char s[]=”Nashik”; is equivalent to s[]={‘N’, ‘a’, ‘s’, ‘h’, ‘i’, ‘k’, ‘\0’};
          i.e.
N
a
s
i
k
\0
String in ‘C’ language has predefined methods stored in string.h.
Methods
Description
strlen(string)
Returns length of string
strcpy(string1,string2)
Copy string2 to string1
strupr(string)
Converts given string to upper case
strlwr(string)
Converts given string to lower case
strcmp(string1,string2)
Compares string1 to string2 and return 3 types of result. Either >0, <0 or =0.
strcat(string1,string2)
concats (merge) string2 to string1
You will find more methods under string.h header file.
How to scan string:
You can scan string by scanf() function. But it does not read space. Hence for scanning complete string as type by user you can use gets() predefined function.
e.g. printf(“\nEnter your name: “);
       gets(string);
gets() is a unformatted function. Look at following example
//string introduction
#include<stdio.h>
#include<conio.h>
void main()
{
 char str[50];
 clrscr();
 printf("\nEnter any string:");
 gets(str);
 printf("String = %s\n",str);
 getch();
}
           
Output:
Enter any string: Nasik City
String = Nasik City
In following program string length is count. As mention above string.h header file has a inbuilt function strlen(). But to clear concept of string, here you have to find length of string by using your logic.
String is a set of characters i.e. you can manipulate it by using array logic. As you have seen at the beginning part, each string end with null character so while handling the string by- one by one character then you should stop whenever null character is encountered. This is use in following program
//program to find string length
#include<stdio.h>
#include<conio.h>
void main()
{
 char str[50];
 int i,len=0,slen=0;
 clrscr();
 printf("\nEnter any string: ");
 gets(str);
 //process
 for(i=0;str[i]!='\0';i++)    //i starts from 0 till null character. Whenever null is encountered then loop gets terminated
 {
  len++;             //It counts characters from beginning to end
  if(str[i]!=32)     //it counts character except space (32 is a ASCII code of space)
  {
   slen++;
  }
 }
 printf("\nTotal length = %d",len);
 printf("\nTotal length without space = %d",slen);
 getch();
}
Output:
Enter any string: Every day is not Sunday
Total length = 23
Total length without space = 19
Let us do this program by library function for finding strings length
//program to find string length
#include<stdio.h>
#include<conio.h>
void main()
{
 char str[50];
 int len;
 clrscr();
printf("\nEnter any string: ");
gets(str);
len = strlen(str);             //No need to apply any logic, only pass your string to strlen() function
printf("\nTotal length = %d",len);
getch();
}
Output:
Enter any string: Every day is not Sunday
Total length = 23
Next program is to print reverse of given string. Here we take two strings namely str1 and str2. We copy str1 to str2 in reverse position. For reversing given string we start reading from end of string to zero position.
//Program to print reverse of string
#include<stdio.h>
#include<conio.h>
void main()
{
 int i,j,len;
 char str1[15],str2[15];
 clrscr();
 printf("\nEnter a string: ");
 gets(str1);
 len=strlen(str1);            //find out the length
 for(i=0,j=len-1;j>=0;i++,j--)         //set j at len-1 i.e. last character of string
 {
   str2[i]=str1[j];
 }
 str2[i]='\0';        //str2 should be terminated by null before print for output
 printf("\nReverse of string  = %s",str2);
 getch();
}
Output:
Enter a string: march
Reverse of string  = hcram
//program to count total number of vowels
#include<stdio.h>
#include<conio.h>
void main()
{
 char str[40],v[10]="aeiouAEIOU";
 int i,j,vow=0;
 clrscr();
 printf("\nEnter any string: ");
 gets(str);
 for(j=0;j<10;j++)
 {
  for(i=0;str[i]!='\0';i++)
  {
   if(str[i]==v[j])              //Compare one by one character from v string to str string
   {
    vow++;                     //counter for vowel gets incremented
   }
  }
 }
 printf("\nTotal number of vowels = %d",vow);
 getch();
 }
}
Output:
Enter any string: computer training institute
Total number of vowels = 10
Following program merge two strings into third string. First store characters of str1 to str3 and then read str2 and put it in str3 from the location where str1 is finished. 
//program to concat two strings
#include<stdio.h>
#include<conio.h>
void main()
{
 char str1[10],str2[10],str3[20];
 int i,k=0;          //k is taken for str3
 clrscr();
 printf("\nEnter 1st string: ");
 gets(str1);
 printf("\nEnter 2nd string: ");
 gets(str2);
 //process
 for(i=0;str1[i]!='\0';i++)
 {
  str3[k] = str1[i];                        //stores str1 to str3
  k++;
 }
 for(i=0;str2[i]!='\0';i++)
 {
  str3[k] = str2[i];                        //stores str2 to str3
  k++;
 }
 str3[k] = '\0';     //terminates str3 by null
 printf("\concatenation of string = %s",str3);
 getch();
}
Output
Enter 1st string: India
Enter 2nd string: Gate
Concatenation of string = IndiaGate



Two Dimensional Character Array

It is similar to two dimensional integer array.
e.g. char s[3][10]={“RED”, ”BLUE”, “GREEN”};
R
E
D
\0
B
L
U
E
\0
G
R
E
E
N
\0
It is use to store list. While processing this type of array we have to check number of rows.  Within rows strings are stored. Every row ends with null (\0) character. Let us handle it through following program.
//scan and print 2-dimensional character array
#include<stdio.h>
#include<conio.h>
void main()
{
 char city[5][25];     //It has 5 rows and 25 columns
 int i;
 clrscr();
 printf("\nEnter name of five cities: \n");
 for(i=0;i<5;i++)
 {
  gets(city[i]);   //value stored rowwise
 }
 //process
printf("\nList of cities:\n");
for(i=0;i<5;i++)
 { 
     printf(str[i]);
 }
 getch();
}
output:
Enter name of five cities:
Mumbai
Pune
Chennai
Delhi
Hydrabad
List of cities:
Mumbai
Pune
Chennai
Delhi
Hydrabad
You can modify above program by using strcmp() library function and print sorted list.
You can perform searching operation i.e. scan string from user and check whether it is present in list or not. Here also you should use strcmp() function.
If you want more string functions and to do study in detail then you can simply set cursor on #include<string.h> and right click the mouse, it will open strings header file containing all string related methods.

No comments:

Post a Comment