Updated September 15, 2023
Introduction to C++ Strings
A string is a library function in C++ that helps perform all the string-related operations in the program. A ‘string’ data type is assigned to a variable containing characters surrounded by double quotations. Any continuous characters assigned to a variable are called a String variable. Here, let us see the usage of String data type in C++ programming language.
Table of Contents
Syntax:
Below is the syntax for the string data type:
string (data type ) trying (variable) = "Test" (Value assigned to variable)
Explanation: The texts written inside the brackets in the above syntax are regarding how the syntax should be understood. According to the syntax above, a variable represented with the ‘string’ data type becomes the string variable, and the string variable is assigned to a value. This part of assigning a variable to its value is called initialization.
Syntax:
string (data type) trying_2 (variable) ("Test in another way") à (value assigned to variable);
In the above representation, the data type and the variable are again assigned to the value without the “equal to” assignment operator using the brackets and quotes.
Rules and Regulations
The main observation that has to be done concerning the C++ string is that “String” is also a library that deals with any C++ functions.
In C++, two types of string representation formats are feasible. One way is using the “char” data type in the C programming language, and the other is using the string data type itself. The “char” data type is used to represent the array. However, using the ‘string’ data type as the ‘char’ array is recommended, which would be defined as static in nature. The extra space gets wasted if the content value is less than the size of the array represented. On the other hand, ‘string’ is dynamic in nature.
One must be careful in assigning and initializing values to “String”. If we look at an initializing value to a string by means of an array, that would give us the error. So, we need to use the “char” data type. Below is an example of the same:
Code:
#include <iostream>
using namespace std;
int main()
{
string ex1="example1";
string ex2[]="example2";
char ex3[]="example3";
cout<<"The first example: "<<ex1<<endl;
cout<<"The second example: "<<ex2<<endl;
cout<<"The third example: "<<ex3<<endl;
}
Output:
- As per the output, the array declaration would give the output of the location of the stored value.
Code:
#include <iostream>
using namespace std;
int main()
{
string big="I am writing many words";
cout<<"The output here is: "<<big;
}
Output:
- Now, let us see how we can change the character in the string given.
Code:
#include <iostream>
using namespace std;
int main()
{
string h="Happy";
cout<<"The output here is: "<<h<<endl;
h[1]='A';
cout<<"The output here is: "<<h;
}
Output:
- Let’s now give the string as the user input value, which is simple and easy.
Code:
#include <iostream>
using namespace std;
int main()
{
string r;
cout<<"Enter any string of your choice"<<endl;
cin>>r;
cout<<"The output here is: "<<r;
}
Output:
- The output you got here is only until the compiler encounters a space.
- Now, to get the whole line that the user had given as input, the following can be done:
Code:
#include
using namespace std;
int main()
{
string r;
cout<<"Enter any string of your choice"<<endl;
getline(cin,r);
cout<<"The Output here is: "<<r;
}
Output:
- Using the “getline” function, we can have the complete user-given input under the output.
- The ‘cstring’ library helps us in such a way that we can use different functions that are built into that library. Some of them are strcat, strcmp, strcpy, strlen, etc., which deal with string concatenating, comparing, copying, and finding the length of the string, respectively.
Examples of C++ Strings Class
Let us see below the example related to a string:
Example #1
Code:
#include <iostream>
using namespace std;
int main()
{
string trying_1="test";
string trying_2 ("Test in another way");
cout<<"Printing the string data type value: "<<trying_1<<endl;
cout<<"Another print data: "<<trying_2;
}
Output:
Example #2
Now, let us take a condition without declaring the namespace.
Code:
#include <iostream>
//using namespace std;
int main()
{
string trying_1="test";
cout<<"Printing the string data type value: "<<trying_1<<endl;
}
Output:
Example #3
Now, what if we use the std function before and check the output:
Code:
#include <iostream>
//using namespace std;
int main()
{
std::string trying_1="test";
std::cout<<"Printing the string data type value: "<<trying_1<<std::endl;
}
Output:
Example #4
Let us have a small program detailing a string library with a char data type:
Code:
#include <iostream>
using namespace std;
#include <cstring>
int main()
{
char r[10]="hello";
char e[5]=" hi";
cout<<"String r is equal to: "<<r<<endl;
cout<<"String e is equal to: "<<e<<endl;
strcat(r,e);
cout<<"The output here is: "<<r;
}
Output:
Try the same by keeping the data type as string instead of char and analyze the output. So here, this is not only for the “String” functions or data type, but using the namespace declaration is important, else we have to use “std” in front of each declaration to make it productive.
C++ Strings Functions
Function | Description | Example |
length() or size() | Returns the length (number of characters) of the string. |
|
append(str) | Appends the given string str to the end of the string. |
|
insert(pos, str) | Inserts the string str at the specified position pos in the string. |
|
replace(pos, len, str) | Replace len characters starting from position pos with the string str. |
|
substr(pos, len) | Extracts a substring of length len starting from position pos. |
|
find(str) | If not found, search for the first occurrence of str in the string and return its position or npos. |
|
rfind(str) | If not found, search for the last occurrence of str in the string and return its position or npos. |
|
compare(str) | Compares the string with str lexicographically and returns an integer (0 if equal). |
|
empty() | Returns true if the string is empty; otherwise, returns false. |
|
clear() | Removes all characters from the string, making it empty. |
|
c_str() | Returns a pointer to the null-terminated C-style character array representation of the string. |
|
Conclusion
So, here we have learned about different modules with respect to C++ Strings programming language. Strings are important in any programming language as they analyze and implement continuous characters. Learning how to use them is necessary in writing any different and complete programs. Keep practicing and enjoy learning C++.
FAQs
Q1. What are C++ strings, and how do they differ from C-style strings?
Ans: In C++, programmers use strings as a data type for storing and handling text. Unlike C-style strings, which are arrays of characters, C++ strings are objects that provide various string manipulation functions and automatic memory management.
Q2. What is the difference between c_str() and data() functions in C++ strings?
Ans: c_str() returns a pointer to a null-terminated character array representing the string’s content, while data() returns a pointer to the string’s internal character array, which may not be null-terminated.
Q3. Are C++ strings mutable?
Ans: Yes, C++ strings are mutable. You can modify the contents of a C++ string using various member functions like insert(), erase(), and replace().
Q4. Are C++ strings null-terminated?
Ans: No, C++ strings are not null-terminated by default. They store their length internally and do not rely on a null character to mark the end of the string.
Recommended Articles
We hope that this EDUCBA information on “C++ Strings” was beneficial to you. You can view EDUCBA’s recommended articles for more information.