C++ Strings

In C++, a string is a sequence of characters, typically used to store and manipulate text. There are two types to represent the strings

1. Using C-style string (character array):

A C-style string is a character array that ends with the null character ‘\0’.

In C++, you can initialize it using double quotes, and the compiler automatically adds the null character at the end.

Syntax:


char array_name[size] = "StringContent";

Explanation:

  • char array_name[]: Declares an array of characters. The size is usually determined automatically by the string literal.
  • StringContent: The string literal is automatically null-terminated.

Example:


#include <iostream>
using namespace std;

int main() {
    char str[] = "Hello, Friends!";
    // Print the string
    cout << str << "\n";
    
    return 0;
}

Output:

Hello, Friends!

2. Using string class

The string class, introduced in the C++ Standard Library, offers a safer and more convenient way to handle strings compared to C-style strings.

Syntax:


#include <string>
string variable_name = "StringContent";

Explanation:

  • string variable_name: Defines a string object in C++.
  • StringContent: A string literal is assigned to the std::string variable.

Example:


#include <iostream>
#include <string>
using namespace std;

int main() {

    string str = "Hello, Friends!";
    
    // Print the string
    cout << str << "\n";
    
    return 0;
}

Output:

Hello, Friends!