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

Variables that can store non-numerical values that are longer than one single character are known as strings. The C++ language library provides support for strings through the standard string class.

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!

C++ Strings – Questions and Answers

Q 1: What is a string in C++?

Ans: A sequence of characters.

Q 2: Which header supports strings?

Ans: <string>

Q 3: Is string a built-in type?

Ans: No, it is a class.

Q 4: Can strings store spaces?

Ans: Yes, using getline().

Q 5: Are strings mutable in C++?

Ans: Yes.

C++ Strings – Objective Questions (MCQs)

Q1. Which header file is required to use the string class in C++?






Q2. Which of the following correctly declares a string in C++?






Q3. What is the default value of a string variable when declared but not initialized?






Q4. Which of the following is NOT a valid way to initialize a string in C++?






Q5. Which namespace is used for strings in C++?






Related C++ Strings Topics