0% found this document useful (0 votes)
15 views6 pages

Chapter 5-Strings

Uploaded by

ShaggY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Chapter 5-Strings

Uploaded by

ShaggY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming I June 2021

Chapter Five Strings in C++


5.1. Overview
A string (also called a character string) is a sequence of contiguous characters in memory
terminated by the NULL character (‘\ 0’). Strings are used in programming language for storing
and manipulating text such as words, names and sentences. It is represented as an array of
characters and end of string is marked by the null character(‘\0’). String constants are enclosed in
double quotes. For instance, “Hello World” is a string.
Array of characters represented a string is defined as follows:
char array-name[size];
For instance, the statement char name[50]; defines an array and reserves 50 bytes memory for
storing a set of characters. The length of this string cannot exceed 49 since one storage location
is reserved for storing the end of the string marker. The following program defines an array and
uses it to store characters.
#include<iostream.h>
int main()
{
char name[50];
cout<< “enter your name<49-max>”;
cin>>name;
cout<< “your name is:”<<name;
return 0;
}
Note:
 A string variable contains a collection of characters surrounded by double quotes
 Example
 Create a variable of type string and assign it a value
 string greeting = "Hello";
 To use strings, you must include an additional header file in the source code, the <string>
library:

5.2. String Manipulation


C++ has several built-in functions such as strlen(), strcat(),strcpy(), etc. for string manipulation.
To use these functions, the header file string.h must be included in the program using the
statement: #include<string.h>
Page | 1
Programming I June 2021

Chapter Five Strings in C++


5.2.1. String length
The string function strlen() returns the length of a given string. A string constant or an array of
characters can be passed as an argument. The length of the string excludes the end of string
character (NULL).
Example
#include<iostream.h> Program Output
#include<string.h>
int main()
{ Enter Your Name: Selam
char s1[25]; strlen(s1): 5
cout<< “Enter your name:”;
cin>>s1;
cout<< “strlen(s1):”<<strlen(s1)<<endl;
return 0;
}
5.2.2. String copy
The string function strcpy() copies the content of one string to another. It takes two arguments,
the first argument is the destination string array and the second argument is the source string
array. The source is copied into the destination string.
Example
#include<iostream.h>
#include<string.h>
int main() Program Output
{
char s1[25],s2[25];
Enter a string: Garbage
cout<< “Enter a string:”;
strcpy(s2,s1): Garbage
cin>>s1;
strcpy(s2,s1);
cout<< “strcpy(s2,s1):”<<s2;
return 0;
}
5.2.3. String Concatenation
The string function strcat() concatenates two strings resulting in a single string. It takes two
arguments, which are the destination and source strings. The destination and source strings are
concatenated and the resulting string is stored in the destination (first) string.
Example
Page | 2
Programming I June 2021

Chapter Five Strings in C++


#include<iostream.h> Program Output
#include<string.h>
int main()
Enter string s1: C
{
Enter string s2: ++
char s1[40],s2[25];
strcat(s1,s2): C++
cout<< “Enter string s1:”;
cin>>s1;
cout<< “Enter string s2:”;
cin>>s2;
strcat(s1,s2);
cout<< “strcat(s1,s2):”<<s1;
return 0;}
5.2.4. String Comparison
The string function strcmp() compares two strings character by character. It accepts two strings
as parameters and returns an integer whose value is :
<0 if the first string is less than the second
==0 if both are identical
>0 if the first string is greater than the second
Whenever two corresponding characters in the string differ, the string which has the character
with the higher ASCII value is greater. For example consider the string hello and Hello. The first
character itself differs. The ASCII code for h is 104, while the ASCII code for H is 72. Since the
ASCII code of h is greater, the string hello is greater than the string Hello. Once a different
character is found, there is no need to compare remaining characters in the string.
Example
#include<iostream.h>
#include<string.h>
int main()
{ Program Output
char s1[25],s2[25];
cout<< “Enter string s1:”;
Enter string s1: Computer
cin>>s1;
Enter string s2: Computing
cout<< “Enter string s2:”;
strcmp(s1,s2): Computer is less than Computing
cin>>s2;
strcat(s1,s2);
int status=strcmp(s1,s2);
cout<< “strcmp(s1,s2):”;
if(status==0)
cout<<s1<< “is equal to ”<<s2;
else if(status>0)
cout<<s1<< “is greater than ”<<s2;
Page | 3
Programming I June 2021

Chapter Five Strings in C++


else
cout<<s1<< “is less than ”<<s2;
return 0;
}

5.2.5. String to Upper/Lower Case


The functions strlwr() and strupr() convert a string to lower case and upper case respectively.
Example
#include<iostream.h>
#include<string.h>
int main() Program Output
{
char s1[25],temp[25];
cout<< “Enter a string :”; Enter a string: Maths
cin>>s1; strupr(temp): MAHS
strcpy(temp,s1); strlwr(temp): maths
cout<< “strupr(temp):”<< strupr(temp)<<endl;
cout<< “strlwr(temp):”<< strlwr(temp)<<endl;
return 0;
}
5.3. More about the C++ string class
string address; Defines an empty string object named address.
string name("William Smith"); Defines a string object named name, initialized with
“William Smith.”
string person1(person2); Defines a string object named person1, which is a copy of
person2. Person2 may be either a string object or character
array.
string set1(set2, 5); Defines a string object named set1, which is initialized to
the first five characters in the character array set2.
string firstName(fullName, 0, 7); Defines a string object named firstName, initialized with a
substring of the string fullName. The substring is seven
characters long, beginning at position 0.
Examples
#include<iostream.h> Program Output
#include<string.h>
int main(){
string str1, str2, str3; ABC
str1 = "ABC"; DEF
str2 = "DEF"; ABCDEF
str3 = str1 + str2; ABCDEFGHI
cout << str1 << endl;
Page | 4
Programming I June 2021

Chapter Five Strings in C++


cout << str2 << endl;
cout << str3 << endl;
str3 += "GHI";
cout << str3 << endl;
return 0; }
5.4. Adding Numbers and Strings
WARNING!

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example
string x = "10";
int y = 20;
string z = x + y;

5.5. Access Strings


You can access the characters in a string by referring to its index number inside square
brackets []. This example prints the first character in myString: For example,
string myString = "Hello";
cout << myString[0]; // Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
Page | 5
Programming I June 2021

Chapter Five Strings in C++


This example prints the second character in myString:
Example
string myString = "Hello";
cout << myString[1];
// Outputs e
5.6. User Input Strings
It is possible to use the extraction operator >> on cin to display a string entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: Asnake
// Your name is: Asnake
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: Asnake Moges


// Your name is: Asnake
From the example above, you would expect the program to print "Asnake Moges", but it only
prints "Asnake". That's why, when working with strings, we often use the getline() function to
read a line of text. It takes cin as the first parameter, and the string variable as second:

Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: Asnake Moges


// Your name is: Asnake Moges

Page | 6

You might also like