Strings in C++
In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.
Creating a String
Creating a string means creating an instance of std::string class as shown:
string str_name;
where str_name is the name of the string.
Initializing a String
Initializing means assigning some initial value to the string. This can be done by using assignment operator and the text enclosed inside “” double quotes.
string str = "Some Text here";
The text inside “” is called string literal and it is the value that is assigned to the string variables. It doesn’t need to have any meaning. It can be any text that is the sequence of characters from the ASCII charset.
Accessing String
A string can be referred using its name anywhere in the scope once it is declared. For example, the below example prints string using cout:
// Creating a string
string greeting = "Welcome to GfG!";
// Accessing string
cout << greeting;
Output
Welcome to GfG!
The individual characters of the strings can also be accessed using their position (or index) like arrays with [] square brackets. The index in C++ starts from 0 and goes till size – 1, so be careful not go outside this limit.
string str = "Sonu";
// Accessing 3rd character
cout << str[2] << endl;
// Accessing first character
cout << str[0];
Output
n S
Updating String
The string variable can be updated store a new string literal in a similar way it is initialized.
string str = "Tara";
cout << str << endl;
// Updating string
str = "Singh";
cout << str;
A single character can also be changed by first accessing the character and then using assignment operator to assign value.
string str = "Tara";
// Updating second character
str[1] = 'o';
Other String Operations
The following operations aims to improve your understanding of the strings in C++ and introduce you to some of the most commonly used operations provided by C++:
Pass Strings to Functions
The string can be passed to a function in the same was as any other type of variable.
// Taking string as argument
void print(string s) {
cout << s;
return;
}
int main() {
string s = "GeeksforGeeks";
// Passing string
print(s);
Output
GeeksforGeeks
C Style Strings
C++ is a superset of C language, so it also inherits the way in which we used to create strings in C. In C, strings were nothing, but an array of characters terminated by a NULL character ‘\0’. They were created as:
char str[] = "Hello";
Due to being array, there were limitations on C strings:
- Fixed Size: Once declared, the size of the C string cannot be changed.
- Lack of Easy String Operations: No high-level operations like concatenation or substring extraction. Moreover, updating was also complex.
C++ strings resolve this issue by providing a lot of operations that are easy to perform. Internally, these strings are still implemented as dynamic array of characters (or more precisely vectors) Thats why we can access a single character by its index. But the std::string class act as a wrapper and provides lot of built-in functionality for easier and more efficient handling of strings.
C++ String vs C Strings
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 be represented as string streams. | The null character terminates a character array of characters. |
No Array decay occurs in strings as strings are represented as objects. | The threat of array decay is present in the case of the character array. |
A string class provides numerous functions for manipulating strings. | Character arrays do not offer inbuilt functions to manipulate strings. |
Memory is allocated dynamically. | The size of the character array has to be allocated statically. |
Know more about the difference between strings and character arrays in C++
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:
Function | Description |
---|---|
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 |
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_back() | This function is used to push the passed character at the end of the string |
pop_back() | This function is used to pop the last character from the string |
clear() | This function is used to remove all the elements of the string. |
strncmp() | This function compares at most the first num bytes of both passed strings. |
strncpy() | This function is similar to strcpy() function, except that at most n bytes of src are copied |
strrchr() | This function locates the last occurrence of a character in the string. |
strcat() | This function appends a copy of the source string to the end of the destination string |
find() | This function is used to search for a certain substring inside a string and returns the position of the first character of the substring. |
replace() | This function is used to replace each element in the range [first, last) that is equal to old value with new value. |
substr() | This function is used to create a substring from a given string. |
compare() | This function is used to compare two strings and returns the result in the form of an integer. |
erase() | This function is used to remove a certain part of a string. |
This function is used to find the string’s last occurrence. |
These functions are discussed in this article in more detail – String Function in C++