C++ Strings

In C++, a string is a sequence of characters stored in an array. A string can be used to represent a word, a sentence, or any other text data. C++ provides two ways to work with strings:

  1. Using an array of characters
  2. Using the string class in the Standard Template Library (STL)

Example 1: Using an Array of Characters

1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 char str[] = "Hello, World!"; 7 cout << "The string is: " << str << endl; 8 return 0; 9}

Output:

The string is: Hello, World!

In the above example, a string is defined using an array of characters. The string is assigned the value "Hello, World!" and then printed to the console.

Example 2: Using the string Class

1#include <iostream> 2#include <string> 3using namespace std; 4 5int main() 6{ 7 string str = "Hello, World!"; 8 cout << "The string is: " << str << endl; 9 return 0; 10}

Output: The string is: Hello, World!

In the above example, a string is defined using the string class in the Standard Template Library (STL). The string is assigned the value "Hello, World!" and then printed to the console.

The string class provides several useful functions for working with strings, such as length, find, substr, and replace. For example, you can use the length function to find the length of a string:

1#include <iostream> 2#include <string> 3using namespace std; 4 5int main() 6{ 7 string str = "Hello, World!"; 8 cout << "The length of the string is: " << str.length() << endl; 9 return 0; 10}

Output: The length of the string is: 13