Strings
String is a collection of characters. C++ provides two types of String representations:
▪ The C-style String (Character Array)
▪ Strings that are objects of string class
The C-Style String (Character Array)
The string can be defined as the one - dimensional array of characters terminated by
a null ('\0').
Declaration of string:
Syntax: char stringname[size];
Ex. char s[20];
String Initialization:
Char s[6]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Char s[]=”hello”;
Note: computer automatically appends a null character(‘\0’) at the end
of the string.
The size of string should be no of characters plus 1.
char name[6]={‘r’,’a’,’h’,’u’,’l’,’\0’};
char name[]=“rahul”;
Here the string “rahul” contains 5 characters so compiler automatically allocates 6
memory locations (1 extra for storing NULL character).
Print String
for(i=0; name[i] != ‘\0’; i++)
{
cout << name[i];
}
Reading & Writing of String using Character Array
char name[12];
cin >> name;
1
cout << name;
#include <iostream>
using namespace std;
int main ()
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << “Welcome message: ";
cout << Hello << endl;
return 0;
OUTPUT
Welcome message: Hello
#include <iostream>
using namespace std;
int main()
char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << “\nEnter another string: ";
cin >> str;
cout << "You entered: " << str << endl;
return 0;
2
OUTPUT
Enter a string: C++
You entered: C++
Enter another string: Programming is fun
You entered: Programming
Note: In the second example, only “Programming” is displayed instead of “Programming
is fun”. This is because the extraction operator >> considers a space “ ” as a terminating
character.
C++ program to read and display an entire line entered by the
user.
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
[Link](str, 100);
cout << "You entered: " << str << endl;
return 0;
}
OUTPUT
Enter another string: Programming is fun
You entered: Programming is fun
▪ To read the text containing the blank space, [Link] function can be used. This
function takes two arguments.
▪ The first argument is the name of the string, and the second argument is the size of the
array.
▪ getline() will take input till it gets a new line(\n) character.
Library Function Use Description
in <cstring>
3
strlen() strlen(“hello”); or computes string's
strlen(s); length
strcpy() strcpy(s1,”hello”); or copies a string to
strcpy(s1,s2); another
strcat() strcat(s1, s2); or Concatenates (joins)
strcat(s1, “hello”); second argument to first argument
strcmp() strcmp(s1, s2); or compares two strings
strcmp(s1, “hello”); or s1, s2 and if they matched returns 0
strcmp(“hello”, s2); or strcmp(s1, otherwise returns non zero value.
“hello”);
String Handling Functions
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char f_name[20];
4
char l_name[20];
char full_name[50];
cout<<"Enter your first name: ";
cin>>f_name;
cout<<"Enter your last name: ";
cin>>l_name;
cout<<"Hi " <<f_name<<"! Your first name has "<<strlen(f_name)<<"
characters."<<endl<<"And your last name has "<<strlen(l_name)<<"
characters."<<endl;
strcpy(full_name,f_name);
strcat(full_name, " ");
strcat(full_name,l_name);
cout<<"Your Full name is: "<<full_name<<endl;
if((strcmp(f_name,l_name))==0)
cout<<"Both strings are equal."<<endl;
else
cout<<"Strings are not equal."<<endl;
return 0;
}
OUTPUT
Enter your first name: John
Enter your last name: Winson
Hi John! Your first name has 4 characters.
And your last name has 6 characters.
Your Full name is: John Winson
Strings are not equal.
Note: For using C-style character strings, <cstring> header must be used.
std::String class
The std::string class provides a convenient way to handle strings in
C++. It is part of <string> header.
5
Declaration and Initialization of string:
Syntax:
#include <string>
std::string str = "Welcome";
OR
std::string str = {"Welcome“};
OR
std::string str {"Welcome“};
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin,str);
cout << "You entered: " << str << endl;
return 0;
}
OUTPUT
Enter a string: Programming is fun
You entered: Programming is fun
▪ getline() will take input till it gets a new line(\n) character.
▪ getline() function takes the input stream as the first parameter, which is cin and str as
the location of the line to be stored.
6
Library Function Description
in <string>
find() Find a substring in the string.
rfind() the last occurrence of a substring in the string.
append() Append to the string.
insert () Append to the string.
erase () Erase characters from the string.
replace () Replace portions of the string.
compare () Compare two strings.
Library Function Description
in <string>
substr() Extract a substring from a string.
length() or size() Returns the length of the string
at() or using array index To access individual characters using array indexing
7
C_str() To obtain a C-style string from a std::string.
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = {"hello"};
string str2 {"Joy"};
string str3 {str2};
string str4 (5,'a'); //Displaying 'a' 5 times
cout<<str1<<endl<<str2<<endl<<str3<<endl<<str4; return 0;
}
OUTPUT
Hello
Joy
Joy
aaaaa
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = {"hello"};
string str2 {str1,3}; //Displaying characters from
index 3 (starting from 0)
string str3 {"Dipika",3}; //Displaying first 3
characters
8
cout<<str1<<endl<<str2<<endl<<str3;
return 0;
}
OUTPUT
Hello
lo
Dip
Example : C++ program to accessing a character from a string
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = {“Welcome Home”};
cout << str[6]<<endl; //Displays character at index 6. No Bound
Checking
cout << [Link](6); //Displays character at 6th index
return 0;
}
OUTPUT
e
e
Example : C++ program to print the string using range based for loop
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = {“Welcome Home”};
9
for(char c:str)
{
cout<<c;
}
return 0;
}
OUTPUT
Welcome Home
Example: C++ program to concatenate two strings and display the
length of a string
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = “Welcome”;
string str2 = "Home";
cout<<str1+str2<<endl; //Concatenates two strings
cout<<[Link](str2); //Append str1 with str2
cout<<str1+" "+str2+ " "+"Joy“<<endl;
cout<< "Length of str1: "<<[Link]()
return 0;
}
OUTPUT
WelcomeHome
WelcomeHome
Welcome Home Joy
Length of str1: 7
Note: For length of the string, size() function can also be used.
Example : C++ program to compare strings
10
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = “Welcome”;
string str2 = "Home"; cout<<(str1==str2)<<endl;
//Compares whether the Strings are same or not
cout<<(str1<str2)<<endl; // Checks the ASCII Value of the
First Character
return 0;
}
OUTPUT
0
0
Example: C++ program to compare strings using compare() function
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = “Welcome”;
string str2 = "Home";
if (([Link](str2)) == 0)
cout << "String Matched" << endl;
else
cout << "String Not Matched" << endl;
return 0;}
OUTPUT
11
String Not Matched
Example: C++ program to display the substring of a string
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = “Welcome Home”;
cout<<[Link](3,2)<<endl; //Display the substring from
index 3. Length of substring is 2.
return 0;
}
OUTPUT
co
C++ program to find the substring of a string
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "Hi! Welcome Home, Joy. Hi";
cout<<[Link]("Jo")<<endl; cout<<[Link]("Jo",19)<<endl;
cout<<[Link]("Hi");
return 0;
}
OUTPUT
18
18446744073709551615
23
Example: C++ program of inserting into a string
12
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "Hi! Welcome Home";
string str1 = "I am Nik";
cout<<[Link](4, "Joy, ")<<endl;
cout<<[Link](4,str1)<<endl; cout<<[Link](21, ".
What will you
have?",4,5);
return 0;
}
OUTPUT
Hi! Joy, Welcome Home
Hi! I am NikJoy, Welcome Home
Hi! I am NikJoy, Welcat wiome Home
Example: C++ program of Replacing a string using replace() function
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "Hey World";
string str2 = "Hello";
[Link](0, 3, str2); // Replaces 3 characters from 0th index
by str2
cout << str1 << endl;
return 0;
13
}
OUTPUT
Hello World
Example: C++ program of erasing a character from a string using
erase() function
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "Hello, World";
// Erase a single character starting from index 5
[Link](5, 1);
cout << str;
return 0;
}
OUTPUT
Hello World
14