Strings In C++ | Create, Manipulate, Functions & More (+Examples)
Table of content:
- What Are Strings In C++?
- Types Of Strings In C++
- How To Declare & Initialize C-Style Strings In C++ Programs?
- How To Declare & Initialize Strings In C++ Using String Keyword?
- List Of String Functions In C++
- Operations On Strings Using String Functions In C++
- Concatenation Of Strings In C++
- How To Convert Int To Strings In C++
- Conclusion
- Frequently Asked Questions
In everyday life, we often think of a string as a piece of thread or fiber. In molecular biology, it might represent a database of protein interactions. Clearly, the term “string” holds various meanings. But what does it mean in programming?
In programming languages like C++, strings refer to a sequence of characters. They are commonly used to store words (i.e., text) or characters (i.e., letters or numbers). In this article, we will discuss everything you need to know about strings, string functions in C++, how to convert integers to strings, and more.
What Are Strings In C++?
As we've mentioned, strings in C++ are used to store textual data made up of a sequence of characters.
- A string variable is a group of characters (including special characters and whitespaces) enclosed in single or double quotation marks.
- For instance, “UNSTOP” and ‘Unstoppable’ are both examples of strings in cpp.
- There are two ways to create a string in C++ programs: by using the C-style strings (character array) and the C++ string using the header file <string> (which offers more functionality and ease).
- The <string> header is also essential when using string functions to manipulate strings,
Note that including the <string> header is essential for working with C++ string functions, allowing us to manipulate strings efficiently.
For Example:
std::string str_name = “ This is the Unstop Blog” ;
Here, we use the string keyword (from <string> header> to indicate that the type of the variable is of type string, followed by the identifier/ name of the variable and the value. We will discuss the declaration process for strings in C++ in the section ahead.
Types Of Strings In C++
As mentioned, strings in C++ language can be represented in two ways:
- C-Style Strings: These are character arrays used to represent strings. This method comes from C programming and requires manual handling of the string's termination using a null character (\0).
- C++ String Class: By using the std::string class, available through the <string> header, you gain access to many powerful string-handling functions that make working with strings easier and safer.
Next, we’ll explore these two methods in greater detail.
How To Declare & Initialize C-Style Strings In C++ Programs?
In C programming language, a string is an array of characters that ends with a null character (\0). The null terminator tells the compiler where the string ends, as arrays don’t inherently know their own length.
C++ also supports C-style character string manipulation with functions like strcpy(), strcmp(), and strcat(). While functional, this method is less common in modern C++ due to the increased complexity and lower safety compared to the C++ string class. The syntax and an example C++ program for this are given below.
Syntax For C-Style Strings In C++:
char array_name[] = {‘ch1’, ‘ch2’, ‘ch3’, ….}; // Array of individual characters
char array_name[] = "string_value"; // String literal
Here,
- The term array_name refers to the name of the array and the char keyword signals that its elements are of character type.
- The square brackets [] or array notation indicate that it is an array, and they can optionally contain the size of the array.
Also seen in the syntax above, you can assign a value to a character array/ C-style string in two ways:
- By listing individual characters enclosed in single quotes inside the curly braces {}. These braces are known as the initializer list.
- By assigning a string value enclosed in double quotes (“ ”).
Examples:
char s1[7] = "unstop"; // C-style string, including null character
char s2[] = "unstop"; // Size deduced automatically
char s3[7] = {'U', 'n', 's', 't', 'o', 'p', '\0'}; // Explicitly adding null character
Here, we initialize the s1 and s2 strings using the double quotes string literal method. We use the individual character inside the curly braces to initialize the last string, s3. The size of these arrays will automatically be 7 characters, where the last is the null terminator (\0), added by the compiler.
Look at the simple C++ program example below, which illustrates how to declare and initialize C-style strings.
Code Example:
Output:
Hello, world!
Code Explanation:
We begin the C++ code example by including the <iostream> header file for input/ output functionality.
- In the main() function, we declare a C-style string or character array named str and assign the value “Hello, world!” to it (using double quotes). The string's end is indicated by the automated addition of the null character (/0) in C++.
- Then, we use the std::cout stream to display the value to the console.
- Finally, the main() function returns 0, indicating successful execution to the operating system.
Note: C-style strings are less common in modern C++ code due to their complexity and lack of safety features.
How To Declare & Initialize Strings In C++ Using String Keyword?
In C++, strings can be declared and initialized using the std::string class, which is part of the C++ Standard Library. Unlike C-style strings (character arrays), the std::string class provides a variety of built-in functions that simplify string manipulation, making it a safer and more flexible option.
To use the string class, you need to include the <string> header in your program. Once included, you use the string keyword to declare and initialize string variables in C++ programs.
Syntax For Creating Strings In C++:
std::string string_name = "string_value";
std::string string_name("string_value");
Here,
- In std::string, the string keyword indicates that the following variable is of string type. The std:: is used to indicate that it is from a library class.
- The name of the string is given by string_name and the value is given by string_value.
As you can see, there are two ways of assigning values to strings in C++ programs:
- In the first method, we use the simple assignment operator (=) to assign the string value enclosed in double quotes.
- In the second method, we directly assign the string value (inside parentheses) using the constructor provided by the std::string class. This approach offers more flexibility, as the string class automatically manages memory, and you don’t need to worry about null terminators.
The basic C++ program example below illustrates both the methods of declaring and initializing a string variable using the string keyword from <string>.
Code Example:
Output:
s1 = Hello
str = Unstop
Code Explanation:
In the C++ code example, we include the <iostream> header for input operations and the <string> header to use the C++ string functionalities.
- In the main() function, we use the string keyword to declare two variables, s1 and str of type string.
- As mentioned in the code comments, we initialize s1 with the value "Hello" using the assignment operator and str with the value "Unstop" using the constructor from the string class.
- The strings are encased in double quotes and are automatically terminated with the null character /0 at the end.
- We then print the values to the console using std::cout statements.
Note: Alternatively, you can include the statement– using namespace std; – after the #include preprocessor directive for header files, to avoid typing std:: every time. However, it's recommended to use the std:: prefix explicitly in larger programs to prevent potential naming conflicts, especially in projects that use multiple libraries.
Declaring & Initializing Empty Strings (Uninitialized String In C++)
You can also declare an empty string, which is simply a string with no initial value. In other words, you can declare a string variable without initializing it at the same point. This is what the syntax would look like:
std::string emptyString;
In this case, emptyString remains uninitialized until a value is assigned to it later in the program.
Check out this amazing course to become the best version of the C++ programmer you can be.
Advantages Of Using The std::string Class
- Automatic Memory Management: The std::string class dynamically manages memory, reducing the risk of buffer overflow and making it safer compared to C-style strings.
- Rich Functionality: The string class offers various built-in functions such as concatenation, comparison, searching, and modifying strings, which are easier to use than C-style functions like strcpy() or strcat().
- Null-Termination: Unlike C-style strings, you don’t need to manually ensure that the string ends with a null character (\0); this is handled automatically.
By utilizing the std::string class, you can handle strings more efficiently and securely in C++ programs. The ability to use operators like = and various constructors offers flexibility when initializing and manipulating strings, making the std::string class the preferred option in modern C++ programming.
List Of String Functions In C++
C++ provides a variety of built-in functions to perform different operations on strings. These functions make it easy to manipulate strings without manually managing memory or handling null characters, as is required with C-style strings. Here are some commonly used string functions in C++:
Function |
Description |
Syntax |
size() |
Returns the size of the string in bytes. |
string_name.size() |
length() |
Returns the length/ number of characters in the string, including spaces. (same as size()). |
string_name.length() |
push_back() |
Appends a character to the end of the string. |
string_name.push_back('char') |
pop_back() |
Removes the last character of the string. |
string_name.pop_back() |
resize() |
Resizes the string to the specified number of characters. If the new size is larger, it adds default characters ('\0'). |
string_name.resize(new_size) |
swap() |
Swaps the contents of two strings. |
string_name1.swap(string_name2) |
find() |
Searches for/ finds the first occurrence of a substring and returns its index. If not found, it returns std::string::npos. |
string_name.find("substring") |
erase() |
Removes/ erases a part of the string, starting from the given position. |
string_name.erase(pos, len) |
compare() |
Compares two strings lexicographically. |
string_name.compare("another_string") |
substr() |
Extracts a substring from the string. It returns a substring starting from a given position and of a specified length. |
string_name.substr(pos, len) |
at() |
Accesses the character at a specified position. |
string_name.at(pos) |
copy() |
Copies characters from a string into a char array. |
string_name.copy(char_array, len, pos) |
capacity() |
Returns the total capacity of the string, i.e., how many characters it can hold without reallocating memory. |
string_name.capacity() |
replace() |
Replaces part of the string with another string. |
str.replace(pos, len, "new_str") |
empty() |
Checks if the string is empty. |
str.empty() |
append() |
Adds another string to the end of the current string. |
str.append("another_str") |
shrink_to_fit() |
Reduces the capacity of the string to fit its size, releasing unused memory. |
str.shrink_to_fit() |
data() |
Returns a pointer to the underlying character array. |
str.data() |
c_str() |
Returns a C-style string (null-terminated character array) equivalent to the string object. |
str.c_str() |
begin() |
Returns an iterator to the first character of the string. Useful for iteration through the string. |
string_name.begin() |
end() |
Returns an iterator to the end of the string. (Marks the end of iteration.) |
string_name.end() |
rbegin() |
Returns a reverse iterator to the end of the string. Starts reverse iteration from the last character. |
string_name.rbegin() |
rend() |
Returns a reverse iterator to the beginning of the string. |
string_name.rend() |
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
Operations On Strings Using String Functions In C++
Now, let’s take a look at some examples of how you can perform various operations on strings in C++ using these functions.
Input String Functions In C++
The following functions are commonly used for input operations on strings:
- getline( ): It is used to read and store an input stream of characters (string including spaces) in the object memory.
- push_back( ): Using this function, you can add the single character passed to the end of the string.
- pop_back( ): This function is used to remove the last character from the string.
Code Example:
Output:
Please enter a string: Hello, world!
Your string is: Hello, world!
Please enter a character to add to the string: ?
Your string with the added character is: Hello, world!?
Removing the last character from the string…
Your string with the last character removed is: Hello, world!
Code Explanation:
- In this example, we declared a string s and initialized it by taking user input using the getline() function.
- We then declared a character variable c and took a single character input from the user.
- After that, we called the push_back() function, which appended the character c to the end of the string s.
- Lastly, we used the pop_back() function, which removed the last character of the string s.
Capacity String Functions In C++
These functions are related to managing the storage capacity of strings in C++:
- capacity( ): This function returns the capacity that the compiler assigned to the string passed as argument.
- resize( ): Used to resize the string to the specified length/ number of characters.
- shrink_to_fit( ): This function reduces the current storage capacity of the string to its current size, releasing the excess space.
Code Example:
Output:
Original string: Hello, world!
Original capacity: 15
After resizing: Hello
Capacity after resizing: 15
Capacity after shrink_to_fit: 5
Code Explanation:
In the C++ example code,
- We declared and initialized string variable s with the value "Hello, world!".
- Then, we called the capacity() function to display the current memory capacity allocated for the string.
- Next, we called resize(5), which truncated the string to the first 5 characters. Even though the string was resized, the memory capacity remained unchanged.
- Finally, we called shrink_to_fit(), which adjusted the memory capacity to match the new size of the string.
Iterator String Functions In C++
These functions provide access to string elements through iterators:
- begin(): This is one of the most commonly used iterator functions that returns an iterator to the start of the string.
- end(): It returns the iterator to the end of the string.
- rend( ): The outcome of this function is a reverse iterator that points to the string's beginning.
- rbegin( ): It retruns a reverse iterator that starts at the end of a string.
Code Example:
Output:
Using forward iterator: Hello, world!
Using reverse iterator: !dlrow ,olleH
Code Explanation:
In this program,
- We declared a string s with the value "Hello, world!".
- Then, we called the begin() function to create an iterator that starts at the first character of the string. We used this iterator in a for loop to print the string in its original order.
- Next, we called the rbegin() function to obtain a reverse iterator starting from the last character of the string and used it in another for loop to print the string in reverse order.
Manipulating String Functions In C++
These functions allow you to copy and swap strings in C++ programs:
- copy(“char array”, len, pos ): Copies a portion of the string into a char array. Three inputs are typically required: the target char array, the length to be copied, and the starting place inside the string to begin copying.
- swap( ): It swaps the contents of one string with another string.
Example C++ program to show manipulating string functions
Output:
Copied substring: world
After swapping: wello, Horld!
Code Explanation:
In this example,
- We declared a string my_string and initialized it with the value "Hello, world!".
- Then, we used the substr() function to copy a portion of the string, starting from index 7 and extracting 5 characters, resulting in the substring "world", and print it to the console.
- Next, we performed a swap operation between the first character (my_string[0]) and the eighth character (my_string[7]), which resulted in the string changing from "Hello, world!" to "wello, horld!".
- Finally, we printed the updated string to the console.
Level up your coding skills with the 100-Day Coding Sprint at Unstop and claim the bragging rights, now!
Concatenation Of Strings In C++
In programming, the concatenation of strings is the process of joining two strings with each other, end to end. For example, say we have two strings- 'Unstop' and 'pable'. Then, the result of string concatenation of these two will be 'Unstoppable'.
For more, read: C++ String Concatenation | All Methods Explained (With Examples)
How To Convert Int To Strings In C++
In C++, converting an integer to a string can be essential when you need to concatenate numbers with text, display numerical values in a textual format, or store integers as strings. In this section, we will explore three common methods for converting integers to strings in C++ langauge:
- to_string()
- boost::lexical_cast
- stringstream class
We will discuss each method with examples and explanations.
Method 1: Using to_string()
The to_string() function in C++ converts an integer (or other primitive types) to its corresponding string representation. It is straightforward and part of the string library.
Syntax:
string to_string (data_type variable_name);
Code Example:
Output:
123
Code Explanation:
- In this example, we first declare an integer variable num and assigned th evalue 123 to it.
- Then, we use the to_string() function to convert it into a string, and store the outcome in the variable str_num.
- After that, we print the string using the cout command.
- Note that the to_string() function is part of the string header, so we included the #include <string> directive at the top of the program.
Method 2: Using boost::lexical_cast
The boost::lexical_cast is part of the Boost library and allows for converting between different types, including strings and integers. Before using it, you need to install Boost on your system.
Syntax:
boost::lexical_cast<data-type>(argument)
Code Example:
Output:
The string "42" as an integer is: 42
Code Explanation:
- In this program, we first declare a string str_num and assign the value “42” to it.
- Then we use the boost::lexical_cast method to convert it to an integer, indicating conversion to integer type (<int>).
- We store the converted value in the variable num and then print it using the cout command.
- Note that if the string is invalid (e.g., "hello"), boost::lexical_cast will throw a boost::bad_lexical_cast exception.
Method 3: Using stringstream Class
The stringstream class allows you to manipulate strings as streams, making it easy to insert and extract values. It’s useful for converting between different types.
Code Example:
Output:
The integer 42 as a string is: 42
Code Explanation:
- In this example, we first declare an integer num and create a stringstream object ss.
- Then, we insert the integer into the stream using the shift operator (<<).
- After that, we extracte the string version using the str() function and store it in the str_num variable.
- Finally, we printed the result using the cout command.
Looking for guidance? Find the perfect mentor from select experienced coding & software experts here.
Conclusion
Strings in C++ are versatile tools for handling textual data/ information. They can be declared and initialized in two primary ways, either using C-style character arrays or by leveraging the std::string class, which offers enhanced functionality. The latter provides several in-built methods for manipulation, comparison, and processing, making it more versatile for modern programming needs.
When dealing with strings, a range of functions like size(), length(), and swap() simplify common operations such as checking length or swapping values between strings. Functions like push_back() and pop_back() help with adding or removing characters, resize() lets you adjust the string size dynamically, and capacity() and shrink_to_fit() allow optimum memory management. In addition we can also convert integers to string, using the simple std::to_string() method or other advanced options like using stringstream for stream-based conversion or boost::lexical_cast for flexible data type conversions.
Mastering these tools are essential when dealing with strings in C++ and will allow you to efficiently manage text, optimize memory usage, and handle data type conversions with ease.
Also read: 51 C++ Interview Questions For Freshers & Experienced (With Answers)
Frequently Asked Questions
Q. Can I use string as a function in C++
No, a string cannot be used as a function in C++. The std::string class represents sequences of characters and includes various methods for handling text (in the string header file), but it does not function as a callable object.
Q. How to declare and initialize a string in C++?
The most common and preferred method of creating strings in C++ language is using the std::string class. For this, you must include the <string> header in the preprocessor directive at the beginning of the program.
Once you have done that, you can create a string like in the following example:
std::string myString = "Hello, world!";
Here, we declared a string variable called myString, using the std::string keyword and assing it a value– “Hello, world!”.
Alternatively you can simply declare a string using the same method, without assigning it any value. This will result in an empty string, as follows:
std::string myString;
The variable myString will remain an empty string until it is assigned a value.
Q. How to concatenate two strings in C++?
There are two ways to concatenate two strings in C++. The most common is the concatenation operator (+), also known as the addition arithmetic operator. Alternatively, you can use the append() method to combine two strings. An example of using the concatenation operator is:
std::string fullName = firstName + " " + lastName;
Here, we are creating a new string called fullName, which combines the strings firstName and lastName with a white space in between
Q. How to get the length of a string in C++?
You can use either length() or size() to get the length of a strings in C++. Both the functions belong to the <string> header.
std::string myString = "Hello";
int len = myString.length();
Here, we first created a string variable called myString and assigned it the value “Hello”. We then call the length() function on mystring using the dot operator. This will return the string length which in this case is 5.
Q. How to convert a string to an integer in C++?
There are multiple ways to transform a string into an integer in C++. You can use either the std::stoi() function or stringstream to convert a string to an integer. For example:
int num = std::stoi("123");
This function will conver the string “123” into the integer value 123. However, then using this function you must ensure proper error handling to avoid exceptions like std::invalid_argument or std::out_of_range.
Q. How to extract a substring from a string in C++?
Use the substr() function to extract part of a string or a substring from a string in C++ program. The function generally takes two arguments: the starting position (inclusive) and the length of the substring.
std::string sub = myString.substr(2, 5); // Extracts a substring starting at index 2 with length 5
In the snippet above, we extract a substring that begins at the 2nd index position (3rd character) and continues for 5 characters.
Q. How to replace a substring in a string in C++?
You can use the replace() function from the std::string class to replace a part of a string in C++. The function takes three parameters: the starting position from where you want to replace, the length of the substring you want to replace, and the new substring that will replace the original one. For example:
std::string myString = "Hello";
myString.replace(1, 2, "Hi"); // Output:HHilo
Q. Give the difference between a string and a character array.
The table below highlights the key differences between character arrays and strings in C++.
String |
Character Array |
Immutable once defined |
Mutable after creation |
A sequence of characters |
A collection of char values |
Static memory allocation |
|
Stored in the String Constant Pool |
Stored in heap or stack memory |
This compiles our discussion on strings in C++ programing. You might also be interested in reading the following:
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- OOPs Concept In C++ | A Detailed Guide With Codes & Explanations
- Defining Constant In C++ | Literals, Objects, Functions & More
- C++ If-Else Statement | Syntax, Types & More (+Code Examples)
- C++ Find() In Vector | How To Find Element In Vector With Examples
- Difference Between C And C++| Features | Application & More!
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment