Strings in C++ | C++ Strings - Scaler Topics (2023)

Overview

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.

Scope of Article

  • We will cover the different ways of defining strings in C++.
  • We will understand how to take string inputs from the users.
  • We will also cover the different functions used on strings.

What is a 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.

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 array. Here is its syntax.

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

Strings in C++ | C++ Strings - Scaler Topics (1)

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.

Different Ways of Defining a String

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'};// orchar str_name[] = {'h', 'e', 'l', 'l', 'o', '\0'};

    Alternatively, we have:

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

    It is not necessary to utilize all the space allocated to a character array (string):

    char str_name[50] = "hello";

Taking 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;}

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;}

Input:

Enter your city name: New Delhi

Output:

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 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.

ComparisonStringCharacter Array
DefinitionString is a C++ class while the string variables are the objects of this classCharacter array is a collection of variables with the data type char.
Syntaxstring string_name;char arrayname[array_size];
Access SpeedSlowFast
IndexingTo access a particular character, we use "str_name.charAt(index)" or "str[index]".A character can be accessed by its index in the character array.
OperatorsStandard C++ operators can be applied.Standard C++ Operators can not be applied.
Memory AllocationMemory is allocated dynamically. More memory can be allocated at run time.Memory is allocated statically. More memory can not be allocated at run time.
Array DecayArray decay (loss of the type and dimensions of an array) is impossible.Array decay might occur.

Concatenation of Strings

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[] = "Scaler "; char str2[] = "Topics."; strcat(str1, str2); cout << str1 << endl; return 0;}

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;}

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;}

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.

C++ String Functions

The string class in C++ has a huge number of built-in functions. These functions come in handy as they help us easily complete our tasks. These string functions are:

Function NameFunction's Description
int length()Used to find the string length
void swap(string& str1)Used to swap the values of 2 strings
int compare(const string& str1)Used to compare 2 strings
string substr(int position, int length)Used to create a new string of a given length
int size()Used to find the string length in terms of bytes
void resize(int length)Used to resize the string length up to the given no. of characters
string& replace(int pos, int n, string& str1)Used to replace a portion of the string that begins at position pos and is of the length of n characters
string& append(const string& str1)Used to add new characters at the end of a string
char& at(int position)Used to access an individual character at the given position
int find(string& str1, int position, int len)Used to find the string given in the parameter
int find_first_of(string& str1, int position, int len)Used to find the first occurrence of the given sequence
int find_first_not_of(string& str1, int position, int n)Used to search the string for the first character that does not match any characters specified in the string
int find_last_of(string& str1, int position, int n)Used to search the string for the last character of the sequence specified
int find_last_not_of(string& str1, int position)Used to search for the last character that does not match with the sequence specified
string& insert()Used to insert a new character before the character indicated at the given position
int max_size()Used to get the maximum length of a string
void push_back(char c)Used to add a new character at the end of a string
void pop_back()Used to remove the string's last character
string& assign()Used to assign new value to a string
int copy(string& str1)Used to copy the contents of a string into another
begin()Used to return the first character's reference
char& back()Used to return the last character's reference
int capacity()Used to return the allocated space for the string
void clear()Used to remove string's all elements
const_iterator cbegin()Used to point to the string's first element
const_iterator cend()Used to point to the string's last element
const_reverse_iterator crbegin()Used to point to the string's last character
bool empty()Used to check if the string is empty or not
string& erase()Used to remove the characters
const_char* data()Used to copy the string's characters into an array
char& front()Used to return a reference of the string's first character
string& operator=()Used to assign a new value to a string
string& operator+=()Used to insert a new character at the end of a string
char operator[](position)Used to retrieve a character at the position specified
int rfind()Used to search for the string's last occurrence
iterator end()Used to reference the string's last character
reverse_iterator rend()Used to point to the string's first character
void shrink_to_fit()Used to reduce the capacity of the container and make it equal to the size of the string
char* c_str()Used to return pointer to an array containing null-terminated character sequence
const_reverse_iterator crend()Used to reference the first character of the string
allocator_type get_allocator();Used to return the allocated object connected with a string
reverse_iterator rbegin()Used to reference the last character of a string
void reserve(int length)Used to reserve the vector capacity

Operations on Strings

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:

  1. 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;}

    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".

  2. 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;}

    Output:

    Name before using push_back: ScalerName after using push_back: Scaler Topics

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

  3. 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;}

    Output:

    Name before using pop_back: ScalerName 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:

  1. 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;}

    Output:

    The length of string is: 28
  2. 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;}

    Output:

    The length of string is: 15The capacity of string is: 15
  3. 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;}

    Output:

    The original string is: C++ ProgrammingThe 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.

  4. shrink_to_fit() : Theshrink_to_fit()function is used to decrease the string’s capacity to make it equal to the string’sminimumcapacity. 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;}

    Output:

    The capacity of string before using shrink_to_fit is: 28The 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:

  1. 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;}

    Output:

    L e

    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.

  2. 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;}

    Output:

    gn
  3. 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;}

    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.

  4. 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;}

    Output:

    Lea

Manipulating Functions

The most commonly used manipulating functions are:

  1. 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;} 

    Output:

    The copied string is: copy fun
  2. 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;}

    Output:

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.
Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated: 01/27/2023

Views: 5960

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.