You are on page 1of 18

ALIGARH MUSLIM UNIVERSITY

Department of Computer Science


Course: MCA CSM-1101: Problem Solving Using C++
Academic Session 2020-2021
Handout-7
Topic: String handling in C++.
Teacher: Dr. Rafiqul Zaman Khan, Professor
Homepage: http://www.drrafiq.org
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Objectives:
To know what is string and how to handle it in C++?
To know how to read and Print Strings in C++.
To know about some important built-in C++ string functions and how to use them?
To learn about string class and their member functions.

What is String?
A string is any sequence of characters enclosed in double quotes. There is no
separate data type for strings as integer, float or double. The string data
type can be considered as a char array. The difference is that a character
variable can hold only one character but a string can have more than one
character in a character array. For example, a string called name with 9
characters can be declared as:

char name [9] = “I like C” ;

Check for the double quotes, the char array size 9. Here the name can be
considered as one string or as an array of characters. That is if you refer
name it is “I like C” and if you refer name[0] it is „I‟, name[1] is „ „ (a blank),
name[2] is „l‟, name[3] is „i‟, and so on. The last character name[8] is „\0‟
which indicates a NULL character which is not displayed but is stored as last
character of the string to indicate its end.
Note: Strings are stored as arrays of characters and have a special „\0‟
termination character called NULL appended (attached) to them to signify
the end of the string.

Note that if the number of characters including the ‘\0’ is more than the
size of the array the results will be unpredictable. However, if the size of
the array is more than the number of characters the extra spaces after the
last „\0‟ character are kept blank and not referred because the string ends

1
at „\0‟. So, always make sure that the size of the array is sufficient for the
string. For example, the above declaration would be wrong if we write
char name [8] = “I like C” ;

The size can be ignored also. In that case the size is considered as that of
the number of characters specified in the declaration.
char name [ ] = “I like C” ;

String Input/Output:

The easiest way to input strings is by using the C++ library function gets
(means get string). The gets( ) function reads a string of characters
entered at the keyboard until you strike the enter key (carriage return).
The carriage return does not become part of the string; instead a null
terminator „\0‟ is placed at the end.

For example, in the following program fragment


char str[80] ;

gets (str) ;
and if the user enters
Rafiqul Zaman Khan

and presses the enter key the string variable str has the characters
“Rafiqul Zaman Khan” with „\0‟ appended at the end but is not displayed.

Similarly, there is an output function puts ( ) which prints or displays the


value of the string variable. Unlike the cout, which stays on the same line
after printing puts automatically advances the output to the next line after
displaying it.

puts (str) ;

2
Example:

#include<iostream.h>
#include<stdio.h>
void main()
{
char name [81];
cout <<"Please Input name of Max 80 Characters : "<<endl;
gets (name) ; /* reads the name */
cout<<"The output is : "<<endl;
puts (name) ; /* prints the name */
}

Sample Output:

You can also use the cin function for string input by and the cout function for string
output. But the disadvantage with it is that cin interprets a blank as the end of the
particular input value. As a result you can’t read the above line Rafiqul Zaman Khan
with cin using a single string variable. You need to take 3 string variables to read the 3
words as

#include<iostream.h>

void main()
{
char first[10], second[10], third[10] ;

3
cin>>first>>second >>third ;
cout<<"My name is :"<<first<<second<<third<<endl;
}

Built-in String Functions:

Large collections of string processing functions are provided in C++ through


string.h file. So, include the string.h file in the programs to use these
functions. To use the string functions make sure that the size of the array
is sufficient so that the strings are terminated with the „\0‟ character or
the functions will not work properly.

strcat ( string1, string2 ) :

The strcat function concatenates or joins the string1 and string2. A


copy of string2 is put at the end of the string1. Make sure that string1 size
is long enough to hold the resulting string (string1 + string2).

Example:

#include<iostream.h>
#include<string.h>
#include<stdio.h>
void main()
{
char string1[ 81] = "ALIGARH", string2 [ ] = "UNIVERSITY" ;

strcat ( string1, string2) ;


puts ( string1 );

Sample Output:

strcpy ( string1, string2 ) :

4
The strcpy function copies string2 into string1. Again make sure that
string1 size is long enough to hold the resulting string.

Example:

#include<iostream.h>
#include<string.h>
#include<stdio.h>
void main()
{
char string1 [ 81] , string2 [ ] = "ALIGARH MUSLIM UNIVERSITY" ;
strcpy ( string1, string2 ) ;
puts ( string1 ) ;
}

Sample Output:

strcmp ( string1, string2 ) :

The strcmp function compares the string1 to string2 and returns an


integer value to show the status of the comparison. A value of 0 indicates
that the two strings are identical. A value of less than 0 shows that string1
is lexicographically (according to alphabetic ordering) less than string2. A
value of greater than 0 shows that string1 is lexicographically (according to
alphabetic ordering) greater than string2.

Example:

#include<iostream.h>
#include<string.h>

void main()
{
char string1 [ ] = "John Doe" ;
char string2 [ ] = "John Doe" ;
char string3 [ ] = "Jane Doe" ;
char string4 [ ] = "John Does" ;

5
cout<< strcmp (string1, string2)<<endl; // both are equal so returned 0
cout<< strcmp (string1, string3)<<endl; // first string is bigger than second so returned
value 1.
cout<< strcmp (string1, string4)<<endl ; // first string is smaller than second so
returned value -1.

Sample Output:

Note that when the strings are not equal the result may be positive or
negative and not the exact value

strlen ( string1 ) :

The strlen function returns an integer equal to the length of the


stored string including blanks, not including the termination character.

Example:

#include<iostream.h>
#include<string.h>

void main()
{
char string1 [ ] = "ALIGARH MUSLIM UNIVERSITY" ;

int len1=strlen(string1);

cout <<"The Length of string1 is = "<<len1<<endl;

Sample Output:

6
strchr ( string, ch ) :

The strchr function searches string for the first occurrence of ch. This function
only tells whether the string contains ch or not and it will not tell the position of the ch in
the string if found.

Example:

#include<iostream.h>
#include<string.h>

void main()
{

char string [50] = "SUHAIL AHMAD KHAN" ;


char search = 'D' ;
if ( strchr (string, search ) != NULL )
cout<<"Search character found\n" ; /* outputs this message */
else
cout<<"Search character not found\n" ;

Sample Output:

Examples:
/****************************************************************
Problem#1:
Write a program that initializes a character array first of size 50 , character array last of
size 50 and array full of character of size 50 Array first contains the first name , array last
contains the last name, array full joins the two strings together first and last .

*****************************************************************/
#include<iostream.h>
#include<stdio.h>

7
#include<string.h>

void main()
{
char first[50];
char last[50];
char full[50]=" ";

puts("Plz Enter your first name :");


gets(first);

puts("Plz Enter your last name :");


gets(last);

strcat(first, last); // it joins last into first


strcat(full,first);
cout<<"Your full name is : "<<endl;
cout<<full<<endl<<endl;

} // end of main

Sample Output:

/***********************************************************************
Program # 2:

Write a C++ program that uses 5 strings str1, str2, str3, str4, str5 each of size 81.
Let str1="what", str2 = "whatsoever, str3 = "ever", str4 = "whatever".
Then it should do the following:

Join the str3 to str1 and print the str1.


Copy the str1 to the str5 and print str5.
Compare the str5 and str4 and print whether they are equal or not.
Find the lengths of the string str1 and print.

8
Check whether the character 'w' occurs in both the strings str2 and str3 and
prints "yes" if it occurs else prints "No".

Use puts ( ) function for printing strings.

***********************************************************************/
#include<iostream.h>
#include<stdio.h>
#include<string.h>
void main()
{
int i, length_str1;
char str1[81]="what";
char str2[81]="whatsoever";
char str3[81]="ever";
char str4[81]="whatever";
char str5[81];

strcat(str1,str3); // it joins str3 with str1 and assigns result in str1.


puts("After joining str3 with str1 , the new str1 is :");
puts(str1);

strcpy(str5,str1); // it copies str1 into str5.


puts("After coping str1 into str5, the new str5 is :");
puts(str5);

i=strcmp(str5,str4); // it returns 0 when str5 and str4 are equal.


if(i==0)
puts("The str5 and str4 are equal");
else
puts("The str5 and str4 are not equal");

length_str1=strlen(str1); //it calculates length of str1.


cout<<"The length of str1 is : "<<length_str1<<endl;

if(strchr(str2,'w')!=NULL && strchr(str3,'w')!=NULL)


puts("\nYes");
else
puts("\nNo");

} // end of main

Sample Output:

9
Character related standard Library Functions in C++:

C++ provides family character-related Standard functions that facilitate character


manipulations.

To use these function #include <ctype.h> heder file is used.

List of character related functions is given below:

Name Description Example Return


isalnum Tests for alphanumeric isalnum(‘a’) 1
isalpha Tests for alphabetic isalpha(‘a’) 1
iscntrl Tests for control character iscntrl(‘\n’) 1
isdigit Tests for digit isdigit(‘1’) 1
islower Tests for lowercase charter islower(‘a’) 1
isupper Tests for uppercase character isupper(‘A’) 1
ispunct Test for punctuation character ispunct(‘!’) 1
isspace Tests for whitespaces charcter isspace(‘ ‘) 1
toupper Converts characters to uppercase toupper(‘a’) A
tolower Converst characters to lowercase tolower (‘A’) a

/*********************************************************************
Problem#1:
Write C++ Program to convert given string into lower case letters.

***********************************************************************/
#include<iostream.h>
#include<string.h>
#include<ctype.h>
int main()
{
char message[ ]="Aligarh Muslim University";

10
int stop=strlen(message),i;

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


{
cout <<(char) tolower(message[i]);
}
cout<<endl<<endl;
return 0;

Sample Output:

Example#1:

#include<iostream.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{
int i,countup,countlow;
int countspace,countdigit,countpunc,countcontrol_c;
char str[80] = "\n\t\tAligarh Muslim University, 2009-2010 ! . \n";
i=countup=countlow=countspace=countdigit=countpunc=countcontrol_c=0;

while(str[i] !='\0')
{
if(ispunct(str[i]))
countpunc++;
if(iscntrl(str[i]))
countcontrol_c++;
if(isdigit(str[i]))
countdigit++;
if(isspace(str[i]))
countspace++;
if(isupper(str[i]))
countup++;
if(islower(str[i]))
{
countlow++;

11
str[i] = toupper(str[i]);
}
i++;
}

cout<<"The number of digits = "<<countdigit<<endl;


cout<<"The number of spaces = "<<countspace<<endl;
cout<<"Upper case letters = "<<countup<<endl;
cout<<"Lower case letters = "<<countlow<<endl;
cout<<"Punctuation characters = "<<countpunc<<endl;
cout<<"Total control characters = "<<countcontrol_c<<endl;
cout<<str;

return 0;
}

Sample Output:

Example#2:

Write a C++ program that reads a string and print the number of vowels, number of upper
case and number of lower case letters. It should also print the string with the first letter
capitalized and the remaining in lower case.

Solution:

/* Prints the number of vowels, uppercase in a given string. Also capitalize the first letter
of string */

#include<iostream.h>
#include<stdio.h>
#include <string.h>
#include <ctype.h>
int isvowel(char ch); // Function Prototype

12
int main( )
{
char str[81];

int len, i, nvowel=0, nupper=0;

gets(str);

len=strlen(str);
for (i=0; i<=len; i++)
{
if (isvowel(str[i]))
nvowel++;
}

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


{
if (isupper(str[i]))
nupper++;
}

str[0]=toupper(str[0]);
for (i=1; i<=len; i++)
{
str[i]=tolower(str[i]);
}

cout<<"\nNumber of vowels = "<<nvowel<<endl;


cout<<"Number of upper case = "<<nupper<<endl;
cout<<"Capitalised string = "<<str<<endl;
return 0;
}

/* returns true if a given character is a vowel */

int isvowel(char ch)


{
int vowel;
vowel=tolower(ch)=='a' ||
tolower(ch)=='i' ||
tolower(ch)=='o' ||
tolower(ch)=='u' ||
tolower(ch)=='e';
return vowel;
}

13
Sample Output:

String handling using String class of C++:

string s, s1, s2; int i, start, len, start1, len1, start2, len2, newSize;
char c; istringstream istr; // requires <sstream>
char* cs; ostringstream ostr; // requires <sstream>

Methods and operators


Type Method Description
Constructors and destructors
string s; Creates a string variable.
string s(s1); Creates s; initial value from s1.
string s(cs); Creates s; initial value from cs.
Altering
s1 = s2; Assigns s2 to s1.
s1 = cs; Assigns C-string cs to s1.
s1 = c; Assigns char c to s1.
s[i] = c; Sets ith character. Subscripts from zero.
s.at(i) = c; As subscription, but throws out_of_range if i isn't in
string.
s.append(s2); Concatenates s2 on end of s. Same as s += s2;
s.append(cs); Concatenates cs on end of s. Same as s += cs;
s.assign(s2, start, len); Assigns s2[start..start+len-1] to s.
s.clear(); Removes all characters from s
Access
cs = s.c_str(); Returns the equivalent c-string.
s1 = s.substr(start, len); s[start..start+len-1].
c = s[i]; ith character. Subscripts start at zero.
c = s.at(i); As subscription, but throws out_of_range if i isn't in
string.
Size
i = s.length(); Returns the length of the string.
i = s.size(); Same as s.length()

14
i = s.capacity(); Number of characters s can contain without
reallocation.
b = s.empty(); True if empty, else false.
i = s.resize(newSize, padChar);Changes size to newSize, padding with padChar if
necessary.
Searching All searches return string::npos on failure.
i = s.find(c); Position of leftmost occurrence of char c.
i = s.find(s1); Position of leftmost occurrence of s1.
i = s.rfind(s1); As find, but right to left.
i = s.find_first_of(s1); Position of first char in s which is in s1 set of chars.
i = s.find_first_not_of(s1); Position of first char of s not in s1 set of chars.
i = s.find_last_of(s1); Position of last char of s in s1 set of chars.
i = s.find_last_not_of(s1); Position of last char of s not in s1 set of chars.
Comparison
i = s.compare(s1); <0 if s<s1, 0 if s==s1, or >0 if s>s1.
i = s.compare(start1, len1, s1, Compares s[start1..start1+len1-1] to
start2, len2); s1[start2..start2+len2-1]. Returns value as above.
b = s1 == s2 The comparison operators work as expected.
also > < >= <= !=
Input / Output
cin >> s; >> overloaded for string input.
getline(cin, s); Next line (without newline) into s.
cout << s; << overloaded for string output.
istr.str(s); Sets input string stream to s.
s = ostr.str(); Returns string generated in output string stream.

Programming example to use string class:

#include <string>
#include <iostream>

using namespace std;

void main()
{
string a("abcd efg");
string b("xyz ijk");
string c;

cout << a << " " << b << endl; // Output: abcd efg xyz ijk

cout << "String empty: " << c.empty() << endl; // String empty: 1
// Is string empty? Yes it is empty. (TRUE)
c = a + b; // concatenation
cout << c << endl; // abcd efgxyz ijk
cout << "String length: " << c.length() << endl; // String length: 15

15
cout << "String size: " << c.size() << endl; // String size: 15
cout << "String capacity: " << c.capacity() << endl; // String capacity: 15
cout << "String empty: " << c.empty() << endl; // String empty: 0
// Is string empty? No it is NOT empty. (FALSE)
string d = c;
cout << d << endl; // abcd efgxyz ijk

// First character: a
cout << "First character: " << c[0] << endl; // Strings start with index 0 just like C.

string f(" Leading and trailing blanks ");


cout << "String f:" << f << endl;
cout << "String length: " << f.length() << endl; // String length: 37
cout << "String f:" << f.append("ZZZ") << endl; // String f: Leading and trailing
blanks ZZZ
cout << "String length: " << f.length() << endl; // String length: 40

string g("abc abc abd abc");


cout << "String g: " << g << endl; // String g: abc abc abd abc
cout << "Replace 12,1,\"xyz\",3: " << g.replace(12,1,"xyz",3) << endl; // Replace
12,1,"xyz",3: abc abc abd xyzbc
cout << g.replace(0,3,"xyz",3) << endl; // xyz abc abd xyzbc
cout << g.replace(4,3,"xyz",3) << endl; // xyz xyz abd xyzbc
cout << g.replace(4,3,"ijk",1) << endl; // xyz i abd xyzbc
cout << "Find: " << g.find("abd",1) << endl; // Find: 6
cout << g.find("qrs",1) << endl;

string h("abc abc abd abc");


cout << "String h: " << h << endl;
cout << "Find \"abc\",0: " << h.find("abc",0) << endl; // Find "abc",0: 0
cout << "Find \"abc\",1: " << h.find("abc",1) << endl; // Find "abc",1: 4
cout << "Find_first_of \"abc\",0: " << h.find_first_of("abc",0) << endl; // Find_first_of
"abc",0: 0
cout << "Find_last_of \"abc\",0: " << h.find_last_of("abc",0) << endl; // Find_last_of
"abc",0: 0
cout << "Find_first_not_of \"abc\",0: " << h.find_first_not_of("abc",0) << endl; //
Find_first_not_of "abc",0: 3
cout << "Find_first_not_of \" \": " << h.find_first_not_of(" ") << endl; //
Find_first_not_of " ": 0
cout << "Substr 5,9: " << h.substr(5,9) << endl; // Substr 5,9: bc abd ab
cout << "Compare 0,3,\"abc\": " << h.compare(0,3,"abc") << endl; // Compare
0,3,"abc": 0
cout << "Compare 0,3,\"abd\": " << h.compare(0,3,"abd") << endl; // Compare
0,3,"abd": -1
cout << h.assign("xyz",0,3) << endl; // xyz
cout << "First character: " << h[0] << endl; // Strings start with 0 // First character: x

16
}

Sample output:

abcd efg xyz ijk


String empty: 1
abcd efgxyz ijk
String length: 15
String size: 15
String capacity: 15
String empty: 0
abcd efgxyz ijk
First character: a
String f: Leading and trailing blanks
String length: 37
String f: Leading and trailing blanks ZZZ
String length: 40
String g: abc abc abd abc
Replace 12,1,"xyz",3: abc abc abd xyzbc
xyz abc abd xyzbc
xyz xyz abd xyzbc
xyz i abd xyzbc
Find: 6
4294967295
String h: abc abc abd abc
Find "abc",0: 0
Find "abc",1: 4
Find_first_of "abc",0: 0
Find_last_of "abc",0: 0
Find_first_not_of "abc",0: 3
Find_first_not_of " ": 0
Substr 5,9: bc abd ab
Compare 0,3,"abc": 0
Compare 0,3,"abd": -1
xyz
First character: x

17
18

You might also like