Character Array

You might also like

You are on page 1of 13

String – Character array

A string is a group of characters of any length . C++ does not provide string as a data type rather
it implements string as a single dimensional character array . A character array /string is defined
as an array of type char which is terminated by the null character ‘\0’. The (‘\0’) is a character
literal which is an escape sequence.
Declaration of character array
A character array can be declared using the syntax data type array name[size];
The declaration includes the data type char along with name of the array and the maximum size.
For example , if a string is declared as - char name[20];
Although the above array can hold maximum 19 characters(one reserved for ‘\0’), but the
maximum size does not always have to be fully used. So while declaring the character array , the
size should be decided considering the maximum length of the data item it can hold.
Initialization of string
A string of characters can be initialized on declaration by enclosing the characters in double
quotes. The null character will be automatically appended.
char str[] = “Hello”;
The array can also be initialized character by character
char str[] = {‘H’,’e’,’l’,’l’,’o’} ;
or
str[0]=’H’;
str[1]=’e’;
str[2]=’l’;
str[3]=’l’;
str[4]=’o’;
str[5]=’\0’;
Accepting character array from the user
Although string is an array, it is considered as one unit of data item and it is read by the name of
the array (like a variable). The input of the string can be done using cin statement
Example char str[10]; cin>>str;
Although cin can be used to accept the string data from the user, but it cannot be used to accept
any string with a space as a part of it . It is because cin takes space as the data entry
terminator. It will ignore the characters after space , if any. Hence cin be used to accept any
string which has one word in it.
The string can also be accepted from user using the following library functions like :
i. gets() –
This helps to input a string and stores it in the given string/array. The header file to be
used is stdio.h
Syntaxgets(name of the string/character array);
Example
char name[10];
gets(name);
gets() can read a string with ‘ ‘ as a part of it. At the end of the data entry, when user
presses enter , a ‘\0’ character will be added to its end automatically. The ‘\0’ character
indicates end of the string.
In the above example gets() will accept maximum 9 characters as one character will be
reserved for ‘\0’. gets() will automatically add ‘\0’ to a string when enter key is pressed at
the end of data entry.

Character array can also be printed using cout and puts()


i. cout can be used to display the string.
cout<<”The string is – “<<str;
ii. puts() This displays the string on screen and puts the cursor to the newline i.e. prints the
string with \n character . The header file is stdio.h
Example1
puts(name); //name is a character array
or
puts(“check”); //puts() to display string literal
Example 2
puts(“computer”);
puts(“science”);
The above statement will display computer
science
Although both puts() and cout can be used to display string but the difference between cout
statement and puts() function is that puts displays the string and shifts the cursor to the newline
where as cout displays the string and does not shift the cursor to the newline.
Difference between Numeric array and character array
The last character in a character array is reserved for ‘\0’, which indicates end of the character
array or string.
When the name of a numeric array is used with cout statement, it displays the starting address of
the array (in memory), whereas, when name of character array is used in output
function/statement like puts or cout, it displays the entire string . It is because in a character
array, the name of the string indicates the starting address and \0(null) indicates the end of
sting ,till when the data to be displayed is present. When console output statement/function like
cout/puts are used with character array, the display of character data will continue till the ‘\0’
character is encountered.
Manipulation of String
Unlike numeric array, the manipulation of a character array is done in a for loop which
continues, till the ‘\0’ character is encountered.(Not till the maximum size of the array as it is not
necessary that the array will be fully occupied.)
Program
Write a program to input a string and perform the following options in a menu driven interface.
The options are
1. Display length of the string
2. Count and display no. of alphabets, digits and spl. character";
3. Count and display no. of words";
4. Encrypt the string (Every letter and digit should be replaced by the next. 9 should be replace
by 0 and Z/z should be replaced by A/a. All special character (including space) should be
changed to *
#include<iostream.h>
#include<stdio.h>
void main()
{
char str[80];
int l=0, i=0, word=1, ch;
cout<<"Enter the string";
gets(str);
cout<<"1. length of the string";
cout<<"2. Counting no. of alphabets, digits and spl. character";
cout<<"3. Counting no. of words";
cout<<"4. Encryp the string";
cout<<"enter choice -";
in>>ch;
if (ch==1) //length
{
for(i=0; str[i]!='\0';i++) //loop starting from first position of array till \0 character
{
l++;
}
cout<<"length of the string"<<l;
}
if (ch==2) // No. of letters, digits, spl. characters
{
int alpha=0, digits=0, spl=0;
for(i=0; str[i]!='\0';i++) //loop starting from first position of array till \0 character
{
if(str[i] >= 'a' && str[i]<='z' || str[i]>='A' && str[i]<='Z')
alpha++;
else if(str[i] >= '0' && str[i]<='9')
digits++;
else spl++;
}
cout<<"\nNumber of alphabets - "<<alpha;
cout<<"\nNumber of digits - "<<digits<<"\nNumber of spl. Characters - "<<spl;
}
if (ch==3) // No. of words
{
for(i=0; str[i]!='\0';i++) //loop starting from first position of array till \0 character
{
if(str[i] == ' ') //checking for ‘ ‘ as space separates 2 words
word++;
}
cout<<"\nNumber of words"<<word;
}
if (ch==4) // No. of letters, digits, spl. characters
{
for(i=0; str[i]!='\0';i++) //loop starting from first position of array till \0 character
{
if(str[i] >= 'a' && str[i]<='z' || str[i]>='A' && str[i]<='Z')
{
if (str[i]=='z' ) //converting for z and Z to a/A
str[i]='a';
else if (str[i] == 'Z')
str[i] = 'A';
else str[i] = str[i]+1;
}
else if(str[i] >= '0' && str[i]<='9')
{
if (str[i] =='9') //changing 9 to 0
str[i]='0';
else str[i]=str[i]+1;
}
else str[i]= '*';
}
}
}
Program -
Write a program to input two strings and perform the following operations in a menu driven
interface. The options are
1. copy one string to another string";
2. combine 2 strings
3. compare 2 strings (it should display whether string are equal or greater or smaller
4. compare two strings ignoring case

include<iostream.h>
#include<stdio.h> //for gets()
#include<string.h>
#include<ctype.h> // header file for toupper()
#include<conio.h>
void main()
{
char str1[40],str2[40],str3[80], ans;
int i, k, j, f=0, cnt=0,res,ch;
cout<<"Enter the first string";
gets(str1);
cout<<"Enter second string";
gets(str2);
do
{
cout<<"1 : To concatenate two strings \n";
cout<<"2 : To compare two strings(strcmp)\n";
cout<<"3 : To compare two strings(strcmpi)ignoring the case\n";
cout<<"4 : To search for a substring in a string\n";
cout<<"Enter choice - ";
cin>>ch;
switch(ch)
{

case 1 : for(i=0;str1[i] !='\0';i++) ; // end of 1st string as active posn.


for(k=0;str2[k] != '\0';k++)
{
str1[i]=str2[k];
i++;
}
str1[i]='\0';
cout<<" concatanated string - "<<str1;
break;
case 2 : for(i=0,j=0;str1[i]==str2[j];i++,j++)
{
if(str1[i]=='\0'||str[j]=='\0')
break;
}
res=str1[i]-str2[j];
if(res==0)
cout<<"\nstrings equal";
else if(res>0)
cout<<"\nstring1 greater";
else
cout<<"\nstring2 greater";
break;
case 3 : for(i=0,j=0;toupper(str1[i])==toupper(str2[j]);i++,j++)
//toupper() changes the character to upper case.
// Header file - ctype.h
{
if(str1[i]=='\0'||str[j]=='\0')
break;
}
res=toupper(str1[i])-toupper(str2[j]);
if(res==0)
cout<<"\nstrings equal";
else if(res>0)
cout<<"\nstring1 greater";
else
cout<<"\nstring2 greater";
break;
case 4 : for(i=0;str1[i]!='\0';i++)
{
j=0;
if(str1[i]==str2[j])
{
k=i;
for(;str2[j]!='\0';j++)
{
if(str1[i]!=str2[j])
{
f=0;
break;
}
else
{
f=1;
i++;
cnt++;
}
}
}
if(cnt==strlen(str2)) /*To check for first occurrence of
substring in the string*/
break;
}
if(f==1)
cout<<"\nsubstring found at"<<k+1<<"position";
else if(f==0 && str1[i]=='\0')
cout<<"\nsubstring not found";
break;
default : cout<<"Wrong choice";
}
cout<<"want to continue y/n? ";
cin>>ans;
}while(ans=='y' || ans== 'Y');
}
Program
Write a program to input two strings and perform the following operations in a menu driven
interface. The options are
1 Copy the contents of a string in another string
2. Reversing a string (in the same string)\n " ;
3 Reversing the string using another string\n";
4 Check if the string is palindrome \n" ;
5 Search and count a given character in a string \n";

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[40], str2[40],str3[80], ans, temp;
int i,k,j,f=0,cnt=0,res,ch, l=0;
cout<<"Enter the string - ";
gets(str1);
for(i=0;str1[i]!='\0';i++) //loop to count length
{
l++;
}
do
{
cout<<"1 : Copy the contents of a string in another string \n";
cout<<"2:Reversing a string (in the same string)\n " ;
cout<<"3 : Reversing the string using another string\n";
cout<<"4 : Check if the string is palindrome \n" ;
cout<<"5 : Search and count a user given character in a string \n";
cout<<"Enter choice - ";
cin>>ch;

switch(ch)
{
case 1 : for(i=0;str1[i] !='\0';i++) //making a copy
{
str2[i]=str1[i];
}
str2[i]='\0';
cout<<str2;
break;

case 2 : for(i=0, k=l-1; i<l/2; i++,k--) //reversing in the same string


{
temp=str1[i];
str1[i]=str1[k];
str1[k]=temp;
}
cout<<str1;
break;
case 3:for(i=l-1,k=0;i>=0;i--,k++) //reversing in another
{
str2[k]=str1[i];
}
str2[k]='\0';
cout<<str2;
break;
case 4 :l=0; //checking for pallindrome
for(i=0,j=l-1;i<l/2;i++,j--)
{
if(str1[i] != str1[j])
{
f=1;
break;
}
}
if(f==1)
cout<<"\nnot a pallindrome";
else
cout<<"\npalindrome";
break;

case 5 : cout<<"\nenter the character to search- ";


char alpha;
int ctr=0;
cin>>alpha;
for(i=0;str1[i]!='\0';i++)
{
if (str[i]==alpha)
ctr++;
}
if (ctr==0)
cout<<"\nNot found " ;
else
cout<<"\nFound "<<ctr<<" no. of times";
break;
}
cout<<"\nwant to continue y/n?";
cin>>ans;
}while(ans=='y' || ans== 'Y');
}

Program Write a program to accept a string a. Reverse each word and store it in string b
#include<iostream.h>
#include<stdio.h>
#include<string.h>
void main()
{
int c=0,k,pos=0,j=0;
char a[20],b[20];
gets(a);
int l=strlen(a);
for(int i=0;i<=l;i++)
{
if((a[i]==' ')||(a[i]=='\0'))
{
for(k=i-1;k>=pos ;k--)
{
b[j]=a[k];
j++;
}
b[j]=' ';
j++;
pos=i+1;
}
}
b[j]='\0';
cout<<"new string "<<b;
}
Program
Write a program to accept two strings (a and b) from the user. Count how many times string b
appears in a .
#include<stdio.h>
#include<string.h>
void main()
{
int i,k,ctr=0,j=0;
char a[20],b[20];
cout<<"Enter the string: ";
gets(a);
cout<<"Enter the word to be found: ";
gets(b);
for(int l1=0; b[l1]!=’\0’;l1++);//loop to get length of the string b
for(i=0,j=0;s1[i]!='\0';i++)
{
if(s1[i]==s2[0]) //if the first letter of b match with any letter of a
{
for(j=0;s2[j]!='\0';i++,j++) //compares the rest of the lettersof both
{
if(s1[i]!=s2[j]) //
break;
}
i--;
if(j==l1) //if j is equal to the length of b match found
ctr++;
}
}
cout<<"The word occurs "<<ctr<<" times.";
}
/* alternative logic using string functions
#include<iostream.h>
#include<stdio.h>
#include<string.h>

void main()
{
int k,ctr=0,j=0;
char a[20],b[20],c[20];
gets(a);
gets(b);
int l=strlen(a);
int l1=strlen(b);
for(int i=0;i<l;i++)
{
for( j=0,k=i;j<l1;j++)
{
c[j]= a[k++];
}
c[j]='\0';

if(strcmp(b,c)==0)
ctr++;
}
if(ctr==0)
cout<<"Not found";
else
cout<<"Found"<<pos<< " times";
}
*/
Output Questions
1. Give the output of the following code:
char s[20]=”GOODLUCK”;
for(int x=7;x>=0;x--)
{
for(int y=0;y<=x;y++)
cout<<s[y];
cout<<endl;
}
Solution
GOODLUCK
GOODLUC
GOODLU
GOODL
GOOD
GOO
GO
G
2. void main()
{
char text[] ="pOwERALone";
char c = '*';
for(int k=0; text[k] !='\0'; k++)
if (text[k] >='K' && text[k] <= 'P')
text[k] = text[k+1];
else if (text[k] =='E' || text[k] =='e')
text[k] = c;
else if (k %2 ==0)
text[k] = c;
else text [k] = text[k] +1;
cout<<"changed string - "<<text;
}
Output will be : changed string- *w***Bop**

Program2 Write a program to reverse all strings stored in an array


#include<iostream.h>
#include<stdio.h>
#include<string.h>
void main()
{
char str[5][10];
int i,j,k,len;
char ch;
for(i=0;i<5;i++)
{
cout<<"Enter string";
gets(str[i]);
}
for(i=0;i<5;i++)
{
len=strlen(str[i]);
for(j=0,k=len-1;j<len/2;j++,k--)
{
ch=str[i][j];//manipulation of each character within a string of the array
str[i][j]=str[i][k];
str[i][k]=ch;
}
}
for(i=0;i<5;i++)
puts(str[i]);
}
Program 3 Write a program to count number of words in each string and display it
#include<iostream.h>
#include<stdio.h>
void main()
{
char str[5][10];
int i,j,word=1;
char ch;
for(i=0;i<5;i++)
{
cout<<"Enter string";
gets(str[i]);
}
for(i=0;i<5;i++)
{
word=1;
for(j=0;str[i][j]!='\0';j++)
{
if(str[i][j]==' ')
word++;
}
cout<<"\nNo of words in"<<str[i]<<word;
}
}
WAP to check the equality of strings and print which string Is bigger
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char a[20],b[20];
int s1=0,s2=0;
int i,j;
cout<<"enter first string\n";
gets(a);
cout<<"enter second string\n";
gets(b);
for(i=0;a[i]!='\0';i++)
s1=s1+int(a[i]);
for(j=0;b[j]!='\0';j++)
s2=s2+int(b[j]);
if(s1>s2)
cout<<"string "<<a<<" is bigger\n";
else if(s1<s2)
cout<<"string "<<b<<" is bigger\n";
else
cout<<"strings r equal\n";
getch();
}

You might also like