0% found this document useful (0 votes)
202 views59 pages

Strings in C++

C++ strings can be defined using either the std::string class or C-style character arrays. Strings store sequences of characters that represent text or other data. The std::string class provides dynamic size and member functions while C-style strings use null-terminated character arrays. Strings can be passed to functions as arguments and accessed within functions using pointers or iterators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views59 pages

Strings in C++

C++ strings can be defined using either the std::string class or C-style character arrays. Strings store sequences of characters that represent text or other data. The std::string class provides dynamic size and member functions while C-style strings use null-terminated character arrays. Strings can be passed to functions as arguments and accessed within functions using pointers or iterators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 59

______________________________________________________

__________________________

C++ strings are sequences of characters stored in a char array.


Strings are used to store words and text. They are also used to
store data, such as numbers and other types of information. Strings
in C++ can be defined either using the std::string class or the C-
style character arrays.

1. C Style Strings:
These strings are stored as the plain old array of characters
terminated by a null character ‘\0’. They are the type of strings that
C++ inherited from C language.

Syntax:

char str[] = "Justdoit..!";


Example:

// C++ Program to demonstrate strings


#include <iostream>
using namespace std;

int main()
{

char s[] = " Justdoit..!";


cout << s << endl;
return 0;
}

Output
Justdoit..!
2. std::string Class
These are the new types of strings that are introduced in C++ as
std::string class defined inside <string> header file. This provides
many advantages over conventional C-style strings such as
dynamic size, member functions, etc.

Syntax:

std::string str("Justdoit..!");
Example:

// C++ program to create std::string objects


#include <iostream>
using namespace std;
int main()
{

string str("Justdoit..!");
cout << str;
return 0;
}

Output
Justdoit..!
One more way we can make strings that have the same character
repeating again and again.

Syntax:

std::string str(number,character);
Example:

#include <iostream>
using namespace std;

int main()
{
string str(5, 'g');
cout << str;
return 0;
}
Output:

ggggg
Ways to Define a String in C++
Strings can be defined in several ways in C++. Strings can be
accessed from the standard library using the string class. Character
arrays can also be used to define strings. String provides a rich set
of features, such as searching and manipulating, which are
commonly used methods. Despite being less advanced than the
string class, this method is still widely used, as it is more efficient
and easier to use. Ways to define a string in C++ are:

Using String keyword


Using C-style strings
1. Using string Keyword
It is more convenient to define a string with the string keyword
instead of using the array keyword because it is easy to write and
understand.

Syntax:

string s = " Justdoit..!";


string s("Justdoit..!");
Example:

// C++ Program to demonstrate use of string keyword


#include <iostream>
using namespace std;

int main()
{

string s = " Justdoit..!";


string str("Justdoit..!");

cout << "s = " << s << endl;


cout << "str = " << str << endl;

return 0;
}

Output
s = Justdoit..!
str = Justdoit..!
2. Using C-style strings
Using C-style string libraries functions such as strcpy(), strcmp(),
and strcat() to define strings. This method is more complex and not
as widely used as the other two, but it can be useful when dealing
with legacy code or when you need performance.

char s[] = {'g', 'f', 'g', '\0'};


char s[4] = {'g', 'f', 'g', '\0'};
char s[4] = "gfg";
char s[] = "gfg";
Example:

// C++ Program to demonstrate C-style string declaration


#include <iostream>
using namespace std;

int main()
{

char s1[] = { 'g', 'f', 'g', '\0' };


char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";
char s4[] = "gfg";

cout << "s1 = " << s1 << endl;


cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;

return 0;
}

Output
s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg
Another example of C-style string:

#include <iostream>
using namespace std;

int main()
{
string S = " Just do it..!";
cout << "Your string is= ";
cout << S << endl;

return 0;
}

Output
Your string is= Just do it..!
How to Take String Input in C++
String input means accepting a string from a user. In C++. We have
different types of taking input from the user which depend on the
string. The most common way is to take input with cin keyword with
the extraction operator (>>) in C++. Methods to take a string as
input are:

cin
getline
stringstream
1. Using Cin
The simplest way to take string input is to use the cin command
along with the stream extraction operator (>>).

Syntax:

cin>>s;
Example:

// C++ Program to demonstrate string input using cin


#include <iostream>
using namespace std;

int main() {
string s;

cout<<"Enter String"<<endl;
cin>>s;

cout<<"String is: "<<s<<endl;


return 0;
}

Output
Enter String
String is:
Output:

Enter String
Just do it..!
String is: Just do it..!
2. Using getline
The getline() function in C++ is used to read a string from an input
stream. It is declared in the <string> header file.

Syntax:

getline(cin,s);
Example:

// C++ Program to demonstrate use of getline function


#include <iostream>
using namespace std;

int main()
{

string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}

Output
Enter String
String is:
Output:

Enter String
Justdoit..!
String is: Justdoit..!
3. Using stringstream
The stringstream class in C++ is used to take multiple strings as
input at once.

Syntax:

stringstream stringstream_object(string_name);
Example:

// C++ Program to demonstrate use of stringstream object


#include <iostream>
#include <sstream>
#include<string>

using namespace std;

int main()
{

string s = " Justdoit..! to the Moon";


stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}

Output
Justdoit..!
to
the
Moon
How to Pass Strings to Functions?
In the same way that we pass an array to a function, strings in C++
can be passed to functions as character arrays. Here is an example
program:

Example:

// C++ Program to print string using function


#include <iostream>
using namespace std;

void print_string(string s)
{
cout << "Passed String is: " << s << endl;
return;
}

int main()
{

string s = " Justdoit..!";


print_string(s);

return 0;
}

Output
Passed String is: Justdoit..!
Pointers and Strings
Pointers in C++ are symbolic representations of addresses. They
enable programs to simulate call-by-reference as well as to create
and manipulate dynamic data structures. By using pointers we can
get the first character of the string, which is the starting address of
the string. As shown below, the given string can be accessed and
printed through the pointers.

Example:

// C++ Program to print string using pointers


#include <iostream>
using namespace std;

int main()
{

string s = " Justdoit..!";

// pointer variable declared to store the starting


// address of the string
char* p = &s[0];

// this loop will execute and print the character till


// the character value is null this loop will execute and
// print the characters

while (*p != '\0') {


cout << *p;
p++;
}
cout << endl;

return 0;
}

Output
Justdoit..!
Difference between String and Character array in C++
The main difference between a string and a character array is that
strings are immutable, while character arrays are not.
String Character Array

Strings define objects that can


The null character terminates a
be represented as string
character array of characters.
streams.

The threat of
No Array decay occurs in
array decay
strings as strings are
is present in the case of the
represented as objects.
character array

A string class provides Character arrays do not offer


numerous functions for inbuilt functions to manipulate
manipulating strings. strings.

Memory is allocated The size of the character array


dynamically. has to be allocated statically.

C++ String Functions


C++ provides some inbuilt functions which are used for string
manipulation, such as the strcpy() and strcat() functions for copying
and concatenating strings. Some of them are:

Functio
Description
n

length(
This function returns the length of the string.
)

swap() This function is used to swap the values of 2 strings.

size() Used to find the size of string


Functio
Description
n

resize( This function is used to resize the length of the string up


) to the given number of characters.

find() Used to find the string which is passed in parameters

push_ This function is used to push the passed character at


back() the end of the string

pop_b This function is used to pop the last character from the
ack() string

This function is used to remove all the elements of the


clear()
string.

strnc This function compares at most the first num bytes of


mp() both passed strings.

strncp This function is similar to strcpy() function, except that at


y() most n bytes of src are copied

strrch This function locates the last occurrence of a character


r() in the string.

strcat( This function appends a copy of the source string to the


) end of the destination string

This function is used to search for a certain substring


find() inside a string and returns the position of the first
character of the substring.

This function is used to replace each element in the


replac
range [first, last) that is equal to old value with new
e()
value.
Functio
Description
n

substr( This function is used to create a substring from a given


) string.

compa This function is used to compare two strings and returns


re() the result in the form of an integer.

erase() This function is used to remove a certain part of a string.

C++ Strings iterator functions


In C++ inbuilt string iterator functions provide the programmer with
an easy way to modify and traverse string elements. These
functions are:

Functions Description

This function returns an iterator pointing to the


begin()
beginning of the string.

This function returns an iterator that points to the end


end()
of the string.

This function is used to find the string’s last


rfind()
occurrence.

This function returns a reverse iterator pointing to the


rbegin()
end of the string.

This function returns a reverse iterator pointing to the


rend()
beginning of the string.
Functions Description

This function returns a const_iterator pointing to the


cbegin()
beginning of the string.

This function returns a const_iterator pointing to the


cend()
end of the string.

This function returns a const_reverse_iterator


crbegin()
pointing to the end of the string.

This function returns a const_reverse_iterator


crend()
pointing to the beginning of the string.

// C++ Program to demonstrate string iterator functions


#include <iostream>
using namespace std;

int main()
{
// declaring an iterator
string::iterator itr;

// declaring a reverse iterator


string::reverse_iterator rit;

string s = " Justdoit..!";

itr = s.begin();

cout << "Pointing to the start of the string: " << *itr<< endl;

itr = s.end() - 1;

cout << "Pointing to the end of the string: " << *itr << endl;

rit = s.rbegin();
cout << "Pointing to the last character of the string: " << *rit <<
endl;

rit = s.rend() - 1;
cout << "Pointing to the first character of the string: " << *rit <<
endl;

return 0;
}

Output
Pointing to the start of the string: J
Pointing to the end of the string: !
Pointing to the last character of the string: s
Pointing to the first character of the string: G

String Capacity Functions


In C++, string capacity functions are used to manage string size
and capacity. Primary functions of capacity include:

Function Description

length() This function is used to return the size of the string

capacity( This function returns the capacity which is allocated to


) the string by the compiler

This function allows us to increase or decrease the


resize()
string size

shrink_to This function decreases the capacity and makes it


_fit() equal to the minimum.

#include <iostream>
using namespace std;
int main()
{

string s = "Justdoit..!";

// length function is used to print the length of the string


cout << "The length of the string is " << s.length() << endl;

// capacity function is used to print the capacity of the string


cout << "The capacity of string is " << s.capacity()<< endl;

// the string.resize() function is used to resize the string to 10


characters
s.resize(10);

cout << "The string after using resize function is " << s << endl;

s.resize(20);

cout << "The capacity of string before using shrink_to_fit


function is "<< s.capacity() << endl;

// shrink to fit function is used to reduce the capacity of the


container
s.shrink_to_fit();

cout << "The capacity of string after using shrink_to_fit function


is "<< s.capacity() << endl;

return 0;
}

Output
The length of the string is 13
The capacity of string is 15
The string after using resize function is GeeksforGe
The capacity of string before using shrink_to_fit function is 30
The capacity of string...
______________________________________________________
_______

C++ Strings with Explanation & Example

String is a collection of characters. There are two types of C++


Strings commonly used in C++ programming language:

C-strings (C-style Strings)


Strings that are objects of string class (The Standard C++ Library
string class)
The C-strings (C-style Strings) Character String
C-Style strings were introduced with C programming language, and
since C++ supports all features of C language this type can be used
in C++ programming as well. This C-style string is actually a one
dimensional array of characters which is terminated by a null
character ‘\0’

Declaration and Initialization of C-Style strings


Following are the different ways to creating a C-style strings.

char str[] = "C++";


Although, “C++” has 3 character, the null character \0 is added to
the end of the string automatically.

Alternative ways of defining a string


char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};
Example-1 C-style Strings Program
C++ program to display a string entered by user.

#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;
}
Output
Enter a string: C++
You entered: C++

Enter another string: Programming is fun.


You entered: Programming

Notice that, in the second example only “Programming” is displayed


instead of “Programming is fun”.
This is because the extraction operator >> works as scanf() in C
and considers a space ” “ has a terminating character.

Example-2 Program to read full line of text

#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);

cout << "You entered: " << str << endl;


return 0;
}
Output
Enter a string: Programming is fun.
You entered: Programming is fun.

You entered: James

To read the text containing blank space, cin.get function can be


used. This function takes two arguments.
First argument is the name of the string (address of first element of
string) and second argument is the maximum size of the array.
In the above program, str is the name of the string and 100 is the
maximum size of the array.

C-Style Strings Inbuilt Functions


C++ provides many functions to manipulate C-style strings as part
of the <cstring> library. Here are a few of the most useful:

Function
Function Description & Usage
Name
strcpy(s1,
Copies string s2 into string s1.
s2);
strcat(s1,
Concatenates string s2 onto the end of string s1.
s2);
strlen(s1);; Returns the length of string s1.
strcmp(s1, Returns 0 if s1 and s2 are the same; less than 0 if
s2); s1<s2; greater than 0 if s1>s2.
strchr(s1, Returns a pointer to the first occurrence of character
ch); ch in string s1.
strstr(s1, Returns a pointer to the first occurrence of string s2 in
s2); string s1.

The String Class in C++ (Object type strings)


The standard C++ library provides a string class type that supports
all the operations mentioned above, additionally much more
functionality. Unlike using char arrays, string objects has no fixed
length, and can be extended as per your requirement.

Example-1 C++ Strings Program


Run Online

include <iostream>
using namespace std;

int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);
// you can also take input as follows:
// cin>>str;
cout << "You entered: " << str << endl;
return 0;
}
Output
Enter a string: C++ Strings and its types.
You entered: C++ Strings and its types.

You entered: James

C++ Strings
In C++, string is an object of std::string class that represents
sequence of characters. We can perform many operations on
strings such as concatenation, comparison, conversion etc.
C++ String Example
Let's see the simple example of C++ string.

#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Output:

Hello
C++
C++ String Compare Example
Let's see the simple example of string comparison using strcmp()
function.

C++ String Compare Example


Let's see the simple example of string comparison using strcmp()
function.

#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char key[] = "mango";
char buffer[50];
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key,buffer) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
Output:

What is my favourite fruit? apple


What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

Strings in C++

A string in C++ is an object that represents a sequence of


characters. On the other hand, a string in C is represented by
an array of characters. C++ supports C-style strings as well.
The string objects in C++ are more frequently used than the
character arrays because the string objects support a wide
range of built-in functions.

String in C++

A string in C++ is a type of object representing a collection (or


sequence) of different characters. Strings in C++ are a part of
the standard string class (std::string). The string class stores
the characters of a string as a collection of bytes in contiguous
memory locations. Strings are most commonly used in the
programs where we need to work with texts. We can perform
various operations on the strings in C++. For example,
reversing, concatenating, or passing as an argument to a
function.

Syntax
The syntax to create a string in C++ is quite simple. We use the
string keyword to create a string in C++. However, we also need to
include the standard string class in our program before using this
keyword.
string str_name = "This is a C++ string";

Besides the method described above, C++ strings can be created in


many different ways. The alternative ways of defining a string are
explained in the upcoming sections. Before that, let us briefly
introduce the C Style Character Strings.

String vs. Character Array


C++ supports both strings and character arrays. Although both help
us store data in text form, strings, and character arrays have a lot of
differences. Both of them have different use cases. C++ strings are
more commonly used because they can be used with standard
operators while character arrays can not. Let us see the other
differences between the two.

String vs. Character Array


C++ supports both strings and character arrays. Although both help
us store data in text form, strings, and character arrays have a lot of
differences. Both of them have different use cases. C++ strings are
more commonly used because they can be used with standard op-
erators while character arrays can not. Let us see the other differ-
ences between the two.

Comparison String Character Array


String is a C++ class while Character array is a
Definition the string variables are the collection of variables
objects of this class with the data type char.
char
Syntax string string_name;
arrayname[array_size];
Access
Slow Fast
Speed
To access a particular
A character can be
character, we use
Indexing accessed by its index in
"str_name.charAt(index)" or
the character array.
"str[index]".
Comparison String Character Array
Standard C++ operators Standard C++ Operators
Operators
can be applied. can not be applied.
Memory is allocated Memory is allocated
Memory dynamically. More memory statically. More memory
Allocation can be allocated at run can not be allocated at
time. run time.
Array decay (loss of the
Array Decay type and dimensions of an Array decay might occur.
array) is impossible.

The C-Style Character String


In the C programming language, a string is defined as an array of
characters that ends with a null or termination character (\0). The
termination is important because it tells the compiler where the
string ends. C++ also supports C-style strings.

Syntax
We can create the C-style strings just like we create an integer ar-
ray. Here is its syntax.

char str_array[7] = {'S', 'c', 'a', 'l', 'e', 'r', '\0'};

Because we also have to add a null character in the array, the


array's length is one greater than the length of the string.
Alternatively, we can define the above string like this as well:

char str_array[] = "Scaler";

The array str_array will still hold 7 characters because C++


automatically adds a null character at the end of the string. If we
use the sizeof() function to check the size of the array above, it will
return 7 as well.

How to Define a String in C++


Now that we have a basic understanding of strings in C++ let us go
through the different ways of defining a string in C++.

Using the string keyword is the best and the most convenient way
of defining a string. We should prefer using the string keyword
because it is easy to write and understand.

string str_name = "hello";


// or
string str_name("hello");

Then we have the C-style strings. Here are the different ways to
create C-style strings:

char str_name[6] = {'h', 'e', 'l', 'l', 'o', '\0'};


// or
char str_name[] = {'h', 'e', 'l', 'l', 'o', '\0'};

Alternatively, we have:

char str_name[] = "hello";


// or
char str_name[6] = "hello";

It is not necessary to utilize all the space allocated to a character


array (string):

char str_name[50] = "hello";

How to Take String Input

To provide our program(s) input from the user, we generally use the
cin keyword along with the extraction operator (>>). By default, the
extraction operator considers white space (such as space, tab, or
newline) as the terminating character. So, suppose the user enters
"New Delhi" as the input. In that case, only "New" will be considered
input, and "Delhi" will be discarded.

Let us take a simple example to understand this:


#include <iostream>
using namespace std;

int main() {
char str[30];

cout << "Enter your city name: ";

cin >> str;


// The user input will be stored in the str variable

cout << "You have entered: " << str;

return 0;
}

Try it yourself
Input:

Enter your city name: New Delhi

Output:

You have entered: New

In the above example, the user entered "New Delhi" in the input. As
" " is the terminating character, anything written after " " was
discarded. Hence, we got "New" as the output.

To counter this limitation of the extraction operator, we can specify


the maximum number of characters to read from the user's input
using the cin.get() function.

Let us take an example to understand this:

#include <iostream>
using namespace std;
int main() {
char str[50];

cout << "Enter your city name: ";


cin.get(str, 50);

cout << "You have entered: " << str << endl;

return 0;
}

Try it yourself
Input:

Enter your city name: New Delhi

Output:

You have entered: New Delhi

Now, we could get the whole string entered by the user.

Apart from this method, we can also use the getline() function. The
getline() function is explained below in this article.

String Operations in C++


Although the implementation of character arrays is faster than that
of string objects, string objects are widely used in C++ because of
the number of in-built functions it supports. Some of the most
commonly used string functions are as follows:

Input Functions
There are three widely used input functions. These are:

getline() : The getline() function is used to read a string entered by


the user. The getline() function extracts characters from the input
stream. It adds it to the string object until it reaches the delimiting
character. The default delimiter is \n. The delimiter could either be a
character or the number of characters a user can input.
For example:

#include <iostream>
using namespace std;

int main() {
char profession[12];

cout << "Enter your profession: ";


// We will take a maximum of 12 characters as input
cin.getline(profession, 12);

cout << "Your profession is: " << profession;

return 0;
}

Try it yourself
Assume the Input Given by the User is as Follows:

Enter your profession: Software Engineer

The Output Will Look Like This:

Your profession is: Software En

We can observe in the above example that the user input was
"Software Engineer". But, because we had specified a limit of 12
characters, the output we got was the first 12 characters of the input
string, i.e., "Software En".

push_back() : The push_back() function is used to push (add)


characters at the end (back) of a string. After the character is
added, the size of the string increases by 1.

For example:

#include <iostream>
using namespace std;

int main() {
string name = "Scaler";

cout << "Name before using push_back: " << name << endl;

// Let's add the word "Topics" at the end of the above string
name.push_back(' ');
name.push_back('T');
name.push_back('o');
name.push_back('p');
name.push_back('i');
name.push_back('c');
name.push_back('s');

cout << "Name after using push_back: " << name << endl;
return 0;
}

Try it yourself
Output:

Name before using push_back: Scaler


Name after using push_back: Scaler Topics

Using the push_back() function several times, we added the word "
Topics" at the end of the string.

pop_back() : The pop_back() function is used to pop (remove) 1


character from the end (back) of a string. As the character gets
removed, the size of the string decreases by 1.

For example:

#include <iostream>
using namespace std;

int main() {
string name = "Scaler";

cout << "Name before using pop_back: " << name << endl;

// using the pop_back() function


name.pop_back();

cout << "Name after using pop_back: " << name << endl;
return 0;
}

Try it yourself
Output:

Name before using pop_back: Scaler


Name after using pop_back: Scale
As we can see, the last character of the name popped out, and the
string is left with one less character.

Capacity Functions
The most commonly used capacity functions are:

length() : As the name suggests, the length() function returns the


length of a string.

For example:

#include <iostream>
using namespace std;

int main() {
string str = "Calculating length of the string";

cout << "The length of string is: " << str.length() << endl;

return 0;
}

Try it yourself
Output:

The length of string is: 28

capacity() : The capacity() function returns the current size of the


allocated space for the string. The size can be equal to or greater
than the size of the string. We allocate more space than the string
size to accommodate new characters in the string efficiently.

For example:

#include <iostream>
using namespace std;

int main() {
string str = "C++ Programming";

cout << "The length of string is: " << str.length() << endl;
cout << "The capacity of string is: " << str.capacity() << endl;

return 0;
}

Try it yourself
Output:

The length of string is: 15


The capacity of string is: 15

resize() : The resize() function is used to either increase or


decrease the size of a string.

For example:

#include <iostream>
using namespace std;

int main() {
string str = "C++ Programming";
cout << "The original string is: " << str << endl;

// We will keep only the first ten characters of the string


str.resize(10);

cout << "The string after using resize is: " << str << endl;

return 0;
}

Try it yourself
Output:

The original string is: C++ Programming


The string after using resize is: C++ Progra

In the above example, we used the resize() function to change the


number of characters in the string. Because we had specified the
first ten characters in resize(), all the characters after the first 10
were removed from the string.

shrink_to_fit() : The shrink_to_fit() function is used to decrease the


string’s capacity to make it equal to the string’s minimum capacity.
This function helps us save memory if we are sure that no
additional characters are required.

For Example:

#include <iostream>
using namespace std;

int main() {
string str = "Using shrink to fit function";

// using resize
str.resize(17);

cout << "The capacity of string before using shrink_to_fit is: " <<
str.capacity() << endl;

str.shrink_to_fit();

cout << "The capacity of string after using shrink_to_fit is: " <<
str.capacity() << endl;

return 0;
}

Try it yourself
Output:

The capacity of string before using shrink_to_fit is: 28


The capacity of string after using shrink_to_fit is: 17

In the above example, after using the resize() function, we realized


that the string capacity was 28. When we used the shrink_to_fit()
function, the size was reduced to 17.

Iterator Functions
The most commonly used iterator functions are:

begin() : The begin() function returns an iterator that points to the


beginning of the string.

For Example:

#include <iostream>
using namespace std;

int main() {
string str = "Learning C++";

// declaring an iterator
string::iterator it;

it = str.begin();
cout << * it << " ";

it++;

cout << * it;

return 0;
}

Try it yourself
Output:

Le

In the above example, we first had to declare an iterator it. The


address returned by the begin() function was stored in this iterator.
Then, we used *it to print the value stored at the returned address.

end() : This function returns an iterator that points to the end of the
string. The iterator will always point to the null character.

For Example:

#include <iostream>

using namespace std;

int main() {
string str = "Programming";

// declaring an iterator
string::iterator it;

it = str.end();

cout << * it; // nothing will print because the iterator points to \0
it--;

cout << * it;


it--;

cout << * it;

return 0;
}

Try it yourself
Output:

gn

rbegin() : The keyword rbegin stands for the reverse beginning. It is


used to point to the last character of the string.

For example:

#include <iostream>
using namespace std;

int main() {
string str = "Programming";

// declaring a reverse iterator


string::reverse_iterator rit;

rit = str.rbegin();

cout << * rit;


rit++;

cout << * rit;


rit++;

cout << * rit;


return 0;
}

Try it yourself
Output:

gni

The difference between rbegin() and end() is that end() points to the
element next to the last element of the string while rbegin() points to
the last element of a string.

rend() : The keyword rend stands for the reverse ending. It is used
to point to the first character of the string.

For example:

#include <iostream>
using namespace std;

int main() {
string str = "Learning C++";

// declaring a reverse iterator


string::reverse_iterator rit;

rit = str.rend();
rit--;

cout << * rit;


rit--;

cout << * rit;


rit--;

cout << * rit;

return 0;
}

Try it yourself
Output:
Lea

Manipulating Functions
The most commonly used manipulating functions are:

copy() : The copy() function is used to copy one sub-string to the


other string (character array) mentioned in the function's arguments.
It takes three arguments (minimum two), target character array,
length to be copied, and starting position in the string to start
copying. For Example:

#include <iostream>
using namespace std;

int main() {
string str1 = "Using copy function";
char str2[10];

// copying nine chars starting from index 5


str1.copy(str2, 9, 5);

// The last character of a char array should be \0


str2[9] = '\0';

cout << "The copied string is: " << str2;

return 0;
}

Try it yourself
Output:

The copied string is: copy fun

swap() : The swap() function swaps one string with another. For
Example:

#include <iostream>
using namespace std;
int main() {
string fruit1 = "Apple";
string fruit2 = "Orange";

cout << "Before swap - fruit 1 is: " << fruit1 << endl;
cout << "Before swap - fruit 2 is: " << fruit2 << endl << endl;

// swapping
fruit1.swap(fruit2);

cout << "After swap - fruit 1 is: " << fruit1 << endl;
cout << "After swap - fruit 2 is: " << fruit2 << endl;

return 0;
}

Try it yourself
Output:

Before swap - fruit 1 is: Apple


Before swap - fruit 2 is: Orange

After swap - fruit 1 is: Orange


After swap - fruit 2 is: Apple

Concatenation of Strings in C++


Combining two or more strings to form a resultant string is called
the concatenation of strings. If we wish to concatenate two or more
strings, C++ provides us the functionality to do the same.

In C++, we have three ways to concatenate strings. These are as


follows.

1. Using strcat() function


To use the strcat() function, we need to include the cstring header
file in our program. The strcat() function takes two character arrays
as the input. It concatenates the second array to the end of the first
array.
The syntax for strcat is:

strcat(char_array1, char_array2);

It is important to note that the strcat() function only accepts


character arrays as its arguments. We can not use string objects in
the function.

For Example:

#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[50] = "Scaler ";
char str2[] = "Topics.";

strcat(str1, str2);

cout << str1 << endl;

return 0;
}

Try it yourself
The output of the above program is:

Scaler Topics.

2. Using append() function


The append() function appends the first string to the second string.
The variables of type string are used with this function. The syntax
for this function is:

str1.append(str2);

Let us Take an Example:


#include <iostream>
using namespace std;

int main() {
string str1 = "Scaler ";
string str2 = "Topics.";

str1.append(str2);

cout << str1 << endl;

return 0;
}

Try it yourself
Output:

Scaler Topics.

3. Using the '+' operator


This is the easiest way to concatenate strings. The + operator takes
two (or more) strings and returns the concatenated string. Its syntax
is:

str1 + str2;

For Example:

#include <iostream>
using namespace std;

int main() {
string str1 = "Scaler ";
string str2 = "Topics.";

str1 = str1 + str2;

cout << str1 << endl;


return 0;
}

Try it yourself
Output:

Scaler Topics.

It is up to the programmer to use + or append(). Compared to +, the


append() function is much faster. However, in programs that do not
have very long strings, replacing + with append() will not
significantly affect program efficiency. On the other hand, the
strcat() function has some potential performance issues based on
the function's time complexity and the number of times the function
runs in the program. So, in a nutshell, it is best to use the append()
function or the + operator.

Conclusion
Strings in C++ can be defined in two ways: using the string class or
character arrays.
It is more convenient to use string objects over character arrays.
The string class provides many functions for the string objects.
We can take string inputs from the user using the cin keyword or
getline() function.
There are three ways to concatenate strings in C++: using strcat(),
append(), or + operator.

How to Input a String in C++

A string is a linear data structure defined as a collection or


sequence of characters. We can declare a string by declaring a
one-dimensional array of characters. The only difference between a
character array and a string is that a string is terminated with the
null character \0.

In the upcoming sections of this article, we will look at how to input


a string in C++. We have 4 different methods of taking input from
the user depending on the requirement and the form of the input
string.

Introduction
The string data structure is an array or a group of characters. C++
has an inbuilt string class that can be used directly, or we can
implement the arrays of characters to use a string data structure.

We can declare a string by declaring a one-dimensional array of


characters. The only difference between a character array and a
string is that a string is terminated with the null character \0.

We can declare the string in the same way we do for arrays, here
the data type will always be the char of the elements stored in the
string:

char stringArray[5];

Here, char is the data type of the elements stored in the array, and
stringArray is the array's name.

To assign values in the array, we can write:

stringArray[0] = 'h';
stringArray[1] = 'e';
stringArray[2] = 'l';
stringArray[3] = 'l';
stringArray[4] = 'o';

We also have different ways to declare C-style strings:

char stringArray[6] = {'h', 'e', 'l', 'l', 'o', '\0'};

Or

char stringArray[] = {'h', 'e', 'l', 'l', 'o', '\0'};

Alternatively, we can also do:


char stringArray[] = "hello";

or

char stringArray[6] = "hello";

Utilizing all the space allocated to a character array is unnecessary


while declaring its size. Still, it's suggested to allocate only THE
space that the string requires to avoid any extra memory allocation
loss, as we can see in the below stringArray declaration:

char stringArray[15] = "hello";

To return the value present at index 3, we can write:

return stringArray[3];

The output of the above code would be 'l', as the value stored at
index 3 is 'l'.

The character array will look like this:

output-character-array

Various Methods to Input a String


Now, we will see how to input a string in C++. By taking input of
strings, we mean accepting a string from the user input. There are
different types of taking input from the user depending on the
different forms of a string. For example, the string can be a single
word like "Hello," or multiple words separated by a space delimiter
like "I am here to learn various methods to input a string".

In this article, we will closely examine four methods to input a string


according to the requirement or the type of string that needs to be
taken as input.

1. cin()
To provide our program input from the user, we most commonly use
the cin keyword along with the extraction operator (>>) in C++. The
iostream header file is imported using our program's cin() method.

The "c" in cin refers to "character," and "in" means "input". Hence,
cin means "character input".

The cin object is used with the extraction operator >> to receive a
stream of characters.

By default, the extraction operator considers white space (such as


space, tab, or newline) as the terminating character. So, if the user
wanted to take the string "hello" as the input, then cin() method will
take the input as "hello", but on the other hand, suppose the user
enters "I am Nobita" as the input string. Then, in that case, only the
first word, "I" will be considered as the input, and the " am Nobita"
string will be discarded because the cin() method will consider the
white space after "I" as the terminating character.

So, while taking input with the cin() method, it will start reading
when it comes to the first non-whitespace character and then stops
reading when it comes to the next white space.

Syntax

The syntax of taking user input by using the cin() method is:

cin >> name_of_the_string;

Here, we can write the cin keyword along with the extraction
operator (>>), then mention the name of the string to be taken as
the user input.

Example

Let us take a simple example to understand this:

#include <iostream>
using namespace std;

int main() {

char str[6];

cout << "Enter the string as an input:";

cin >> str;


// The user input will be stored in the str variable.

cout << "The entered string was:" << endl;

cout << str << endl;


}

Try it yourself
The output of the above program is:

Enter the string as input:


hello
The entered string was:
hello

Explanation

As we can see from the output above, the string "hello" was taken
as the input from the user and was displayed as the output.

Now, let's take another example: our input string will consist of more
than one word to see the working of cin() method.

#include <iostream>
using namespace std;

int main() {

char str[15];
cout << "Enter the string as an input:";

cin >> str;


// The user input will be stored in the str variable

cout << "The entered string was:" << endl;

cout << str << endl;


}

Try it yourself
The output of the above program is:

Enter the string as input:


I am Nobita
The entered string was:
I

Explanation As we can see from the output above, the string "I am
Nobita" was taken as the input from the user, but only the first word,
"I" was displayed as the output. As " " is the terminating character,
anything written after " " was discarded. Hence, we only got "I" as
the output.

Thus, the cin() method can only extract a single word, not a phrase
or an entire sentence.

This is one of the significant limitations of the cin() method, as we


cannot take input of the string consisting of multiple words
separated by space, tab, or a new line character. This limitation is
caused because we are using an extraction operator, which is the
limitation of the extraction operator >>. To counter this limitation, we
will look at other methods of taking input from the user.

2. getline()
To overcome the limitation we looked at above with the cin()
method, we often use the getline() function to read a line of text or a
sentence. It takes cin as the first parameter and the string variable
as the second parameter.

getline() is a pre-defined builtin-in function defined in a <string.h>


header file. It is used to take input of a sentence from the input
stream until the delimiting character is encountered.

There are two ways of using the getline() method. One is to pass
two parameters, the first being cin and the second being the input
string. The other way is to pass three variables. First, the two
remain the same as above, and the third parameter is the delimiter
character, which we would like to use as a terminating character.

Syntax

Let's see the syntax for both the ways we discussed above:

getline(cin, name_of_the_string);

Another way is also to provide the delimiter character at which we


want to terminate:

getline(cin, name_of_the_string, delimiter_character);

Here, name_of_the_string denotes the string variable's name, and


delimeter_character is the terminating character.

Example

#include <iostream>
#include<string.h>
using namespace std;

int main() {
// String variable declaration.
string str;

cout << "Enter the string as an input:";


getline(cin, str); // Implementing a getline() function.
// The user input will be stored in the str variable.

cout << "The entered string was:" << endl;

cout << str << endl;

Try it yourself
The output of the above program is:

Enter the string as input:


I am Nobita
The entered string was:
I am Nobita

Explanation As we can see from the output above, the string "I am
Nobita" was taken as the input from the user, and the same was
displayed as the output, which means that the getline() function
accepts the character even when the space character is
encountered.

Let's see another example of using the getline() function to take


input from the user, along with passing the delimiter character as a
third parameter to the getline() function.

#include <iostream>
#include<string.h>
using namespace std;

int main() {
// String variable declaration.
string str;

cout << "Enter the string as an input:";

getline(cin, str, ' '); // Implementing a getline() function.


// The user input will be stored in the str variable.
cout << "The entered string was:" << endl;

cout << str << endl;

Try it yourself
The output of the above program is:

Enter the string as input:


I am Nobita
The entered string was:
I

Explanation As we can see from the output above, the string "I am
Nobita" was taken as the input from the user, but only "I" was
displayed as the output this time because we have also added the
delimiting character(' ') space as a third parameter. Here, the
delimiting character is a space character, which means the string
that appears after space will not be considered. Only the string
which appeared before the delimiting character will be displayed in
the output string.

Let's try another example with a different delimiter to understand the


concept of the getline() function.

#include <iostream>
#include<string.h>
using namespace std;

int main() {
// String variable declaration.
string str;

cout << "Enter the string as an input:";

getline(cin, str, '?'); // Implementing a getline() function.


// The user input will be stored in the str variable.
cout << "The entered string was:" << endl;

cout << str << endl;

Try it yourself
The output of the above program is:

Enter the string as input:


What is your age? I am 19
The entered string was:
What is your age

Explanation As we can see from the output above, the string "What
is your age? I am 19" was taken as the input from the user, but only
"What is your age" was displayed as the output because here we
have added the delimiting character as ('?') as a third parameter.
Here, the delimiting character is a question mark character, which
means the string that appears after the question mark will not be
considered. Only the string which appeared before the delimiting
character will be displayed in the output string.

Thus, the getline() function takes inputs for longer strings, which will
keep appending them to the string until it encounters a delimiting or
a terminating character.

3. gets()
The gets() method in C reads characters until a new line occurs or
you press enter or a return key. We can use this while taking input
from the user as a string with multiple words. A complete sentence
can be captured with the help of a gets() function. It is used to
overcome the limitation of the cin() method. So, the gets() method
allows the user to enter the space-separated strings.

The difference between gets() and getline() is that gets() is a C


function, and getline is a function in C++. As we can use all the C
functions in C++, you get the gets() function to use in C++ along
with C.

Another difference between the working of gets() and getline() is


that gets() extracts character by character from a stream and
returns its value, whereas getline() extracts in a line-by-line format.

Syntax

Let's see the syntax of using the gets() function:

gets(name_of_the_input_string);

Here, name_of_the_input_string denotes the user input string.

Example

Let's see a simple example to understand the use of gets():

#include<stdio.h>

int main() {
// String variable declaration.
char str[30];

printf("Enter the string as an input:\n");

gets(str);
// The user input will be stored in the str variable.

printf("The entered string was:\n");;

printf("%s", str);

Try it yourself
The output of the above program is:
Enter the string as input:
My name is Riya.
The entered string was:
My name is Riya.

Explanation As we can see from the output above, the string


entered by the user is displayed the same in the output.

But, the gets() function is sometimes risky since it doesn't perform


any array bound checking and keeps reading the characters until
the new line or the Enter is encountered. So, it can suffer from
buffer overflow, as it will still print the whole string sentence even
though the maximum limit of characters is crossed, leading to a
buffer overflow.

To avoid this, we can use the fgets() method, ensuring that no more
than the maximum limit of characters is read.

Let's understand this with the help of an example:

#include<stdio.h>

int main() {
char str[6];

printf("Enter the input string:\n");

fgets(str, 6, stdin);

printf("The entered string was:\n");


printf("%s", str);
}

Try it yourself
The output of the above program is:

Enter the string as input:


My name is Riya.
The entered string was:
My na

Explanation As we can see from the output above, the string


displayed was "My na" only, as the maximum limit (6, one for a null
character) of the character array was reached.

Thus, it is safe to use fgets() because it checks the array bound and
keeps reading until a newline character is encountered or the
maximum limit of the character array is reached.

4. stringstream()
stringstream() associates a string object with a stream, allowing you
to read from the string like a stream. It is mainly used to "split" the
string into different words treating the given string as a stream.

To use stringstream, we need to include the sstream header file.

Syntax

Let's see the syntax to use stringstream():

stringstream name_of_stringstream_object(name_of_input_string);

Here, name_of_stringstream_object represents the name of the


stringstream object, which will break and store the original string
(i.e., name_of_input_string in the syntax) into words.

Example

Let's see an example of counting the number of words in a string


with the help of the stringstream() method:

#include <iostream>
#include <sstream>
#include<string>
using namespace std;

int totalWords(string str) {


// Used for breaking input into words.
stringstream new_str(str);

// To store individual words.


string word;

// Used to count the number of words in a given string.


int count = 0;

// >> operator allows us to read from the stringstream object.


while (new_str >> word) {
count++;
}

return count;
}

int main() {
string str = "I am here to learn stringstream";

int count = totalWords(str);

cout << "Total number of words in a given string are:" << " " <<
count << endl;
}

Try it yourself
The output of the above code is:

The total number of words in a given string is 6

Explanation As we can see from the above code, we have used the
stringstream object new_str to break the input string into words.
Then we extracted individual words one by one from the
stringstream object, and each time when a new word was extracted,
we incremented the count of the words in our count variable.
Hence, the total number of words in the string "I am here to learn
stringstream" is 6.
Let's see another application of stringstream in C++ to print the
frequencies of different words in a given string.

It will print how often each word has occurred in a given string.

In this example, we will use a map data structure, as it has pairs of


keys and values, where each word in the string will act as a key,
and its corresponding value is the frequency of that particular word.

#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include<string>
using namespace std;

void freq(string str, map<string, int>& m){

// Used for breaking words.


stringstream new_str(str);

// To store individual words.


string Word;

// Reading individual words.


while (new_str >> Word) {
m[Word]++;
}
}

int main() {
string str = "I am a tech geek and I will make you a geek also";

// Each word in a map will be mapped to its frequency.


map<string, int> m;

// Calling the function to calculate the frequency of words.


freq(str, m);

// Traversing map to print the key and values.


for(auto x: m) {
cout << x.first << "->" << x.second << endl;
}
}

Try it yourself
The output for the above code is:

I->2
a->2
also->1
am->1
and->1
geek->2
make->1
tech->1
will->1
you->1

Explanation As you can see from the output, each word and its
frequency of occurrence are displayed.

Conclusion
A string is a linear data structure defined as the collection or a
sequence of characters. We can declare a string by declaring a
one-dimensional array of characters. The only difference between a
character array and a string is that a string is terminated with the
null character \0.
In this article, we looked at how to input a string in C++ and
discussed different methods and examples.
The cin object and the extraction operator >> are used to receive a
stream of characters as a user input string.
While taking input with the cin() method, it will start reading when it
comes to the first non-whitespace character and then stops reading
when it comes to the next white space.
So, the cin() method can only extract a single word, not a phrase or
an entire sentence.
The gets() method in c reads characters until a new line occurs or
you press enter or a return key.
fgets() method is used to avoid buffer overflows as it checks the
array bound, so it is safer to use than the gets() method.
stringstream() method associates a string object with a stream
allowing you to read from the string as if it were a stream. It is
mainly used to "split" the string into different words treating the
given string as a stream.
Using the <sstream> header file, you can convert a given string into
a StringStream object. For this, you need to use the type
stringstream to create a constructor and pass the given string as
input.
getline() method takes an input of a sentence from the input stream
until the delimiting character is encountered. If we do not add or
specify any delimiting character in a getline() function, it will read
characters until a new line occurs or you press enter or a return key.

You might also like