String in C++

String in C++

String in C++

In C++ string is a sequence of characters represented as an object of the string class. The string class provides many way to handle string.

To use the string class, you need to include the <string> header file. Here’s an example of how to declare a string variable and assign a value to it:

				
					#include<iostream>

#include<string>

using namespace std;

int main() {

   string str = "Hello, world!";

   cout << str << endl;

   return 0;

}
				
			

In the above example, we declare a string variable str and assign the value “Hello, world!” to it. We then use the cout statement to display the value of str on the console.

You can also concatenate two or more strings using the + operator or the append() function:

				
					#include<iostream>

#include<string>

using namespace std;

int main() {

   string str1 = "Hello";

   string str2 = "world";

   string str3 = str1 + " " + str2;

// using + operator

   str3.append("!"); // using append() function

   cout << str3 << endl;

   return 0;

}
​
				
			

In the above example, we declare three string variables str1, str2, and str3. We concatenate str1, a space, and str2 using the + operator and assign the result to str3. We then append an exclamation mark to str3 using the append() function. Finally, we display the value of str3 on the console.

The string class provides many other functions for manipulating strings, such as length(), substr(), replace(), and find(). You can refer to the C++ documentation for more information on these functions.

Join To Get Our Newsletter
Spread the love