Strings in C++
Strings in C++
__________________________
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:
int main()
{
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:
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:
Syntax:
int main()
{
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.
int main()
{
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:
int main() {
string s;
cout<<"Enter String"<<endl;
cin>>s;
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:
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:
int main()
{
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:
void print_string(string s)
{
cout << "Passed String is: " << s << endl;
return;
}
int main()
{
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:
int main()
{
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
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
Functio
Description
n
length(
This function returns the length of the string.
)
pop_b This function is used to pop the last character from the
ack() string
Functions Description
int main()
{
// declaring an iterator
string::iterator itr;
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
Function Description
#include <iostream>
using namespace std;
int main()
{
string s = "Justdoit..!";
cout << "The string after using resize function is " << s << endl;
s.resize(20);
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...
______________________________________________________
_______
#include <iostream>
using namespace std;
int main()
{
char str[100];
return 0;
}
Output
Enter a string: C++
You entered: C++
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
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.
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.
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.
#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:
Strings in C++
String in C++
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";
Syntax
We can create the C-style strings just like we create an integer ar-
ray. Here is its syntax.
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.
Then we have the C-style strings. Here are the different ways to
create C-style strings:
Alternatively, we have:
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.
int main() {
char str[30];
return 0;
}
Try it yourself
Input:
Output:
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.
#include <iostream>
using namespace std;
int main() {
char str[50];
cout << "You have entered: " << str << endl;
return 0;
}
Try it yourself
Input:
Output:
Apart from this method, we can also use the getline() function. The
getline() function is explained below in this article.
Input Functions
There are three widely used input functions. These are:
#include <iostream>
using namespace std;
int main() {
char profession[12];
return 0;
}
Try it yourself
Assume the Input Given by the User is as Follows:
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".
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:
Using the push_back() function several times, we added the word "
Topics" at the end of the string.
For example:
#include <iostream>
using namespace std;
int main() {
string name = "Scaler";
cout << "Name before using pop_back: " << name << endl;
cout << "Name after using pop_back: " << name << endl;
return 0;
}
Try it yourself
Output:
Capacity Functions
The most commonly used capacity functions are:
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:
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:
For example:
#include <iostream>
using namespace std;
int main() {
string str = "C++ Programming";
cout << "The original string is: " << str << endl;
cout << "The string after using resize is: " << str << endl;
return 0;
}
Try it yourself
Output:
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:
Iterator Functions
The most commonly used iterator functions are:
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++;
return 0;
}
Try it yourself
Output:
Le
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>
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--;
return 0;
}
Try it yourself
Output:
gn
For example:
#include <iostream>
using namespace std;
int main() {
string str = "Programming";
rit = str.rbegin();
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++";
rit = str.rend();
rit--;
return 0;
}
Try it yourself
Output:
Lea
Manipulating Functions
The most commonly used manipulating functions are:
#include <iostream>
using namespace std;
int main() {
string str1 = "Using copy function";
char str2[10];
return 0;
}
Try it yourself
Output:
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:
strcat(char_array1, char_array2);
For Example:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[50] = "Scaler ";
char str2[] = "Topics.";
strcat(str1, str2);
return 0;
}
Try it yourself
The output of the above program is:
Scaler Topics.
str1.append(str2);
int main() {
string str1 = "Scaler ";
string str2 = "Topics.";
str1.append(str2);
return 0;
}
Try it yourself
Output:
Scaler Topics.
str1 + str2;
For Example:
#include <iostream>
using namespace std;
int main() {
string str1 = "Scaler ";
string str2 = "Topics.";
Try it yourself
Output:
Scaler Topics.
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.
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 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.
stringArray[0] = 'h';
stringArray[1] = 'e';
stringArray[2] = 'l';
stringArray[3] = 'l';
stringArray[4] = 'o';
Or
or
return stringArray[3];
The output of the above code would be 'l', as the value stored at
index 3 is 'l'.
output-character-array
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.
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:
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
#include <iostream>
using namespace std;
int main() {
char str[6];
Try it yourself
The output of the above program is:
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:";
Try it yourself
The output of the above program is:
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.
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.
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);
Example
#include <iostream>
#include<string.h>
using namespace std;
int main() {
// String variable declaration.
string str;
Try it yourself
The output of the above program is:
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.
#include <iostream>
#include<string.h>
using namespace std;
int main() {
// String variable declaration.
string str;
Try it yourself
The output of the above program is:
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.
#include <iostream>
#include<string.h>
using namespace std;
int main() {
// String variable declaration.
string str;
Try it yourself
The output of the above program is:
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.
Syntax
gets(name_of_the_input_string);
Example
#include<stdio.h>
int main() {
// String variable declaration.
char str[30];
gets(str);
// The user input will be stored in the str variable.
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.
To avoid this, we can use the fgets() method, ensuring that no more
than the maximum limit of characters is read.
#include<stdio.h>
int main() {
char str[6];
fgets(str, 6, stdin);
Try it yourself
The output of the above program is:
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.
Syntax
stringstream name_of_stringstream_object(name_of_input_string);
Example
#include <iostream>
#include <sstream>
#include<string>
using namespace std;
return count;
}
int main() {
string str = "I am here to learn stringstream";
cout << "Total number of words in a given string are:" << " " <<
count << endl;
}
Try it yourself
The output of the above code is:
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.
#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include<string>
using namespace std;
int main() {
string str = "I am a tech geek and I will make you a geek also";
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.