Topic 36 of 91 6. C++ Arrays and Strings Interactive Tutorial

Strings in C++: Character Sequences, std::string, and Common Operations

16 mins read Last updated: 26 Sep 2026 24,900 views

Direct Answer & Core Concept

Strings are an important part of almost every programming language. They allow programs to store and process text such as names, addresses, messages, email addresses, and user input.

In C++, strings can be handled using character arrays or the standard library's std::string class.

For example, a program might need to:

  • Store a user's name.

  • Read a sentence from the keyboard.

  • Join two strings together.

  • Find the length of a string.

  • Search for a particular word.

  • Replace or remove characters.

  • Compare two strings.

Detailed Explanation & Mechanics

1. What Is a String in C++?

A string is a sequence of characters used to represent text.

For example:

Here, name stores the text "Admin".

Strings can contain:

  • Alphabetic characters: "Hello"

  • Numeric characters: "12345"

  • Special characters: "@#$%"

  • Spaces: "Welcome to C++"

  • Mixed characters: "User123"

C++ provides two common ways to represent strings:

  1. C-style strings using character arrays.

  2. C++ strings using the std::string class.

2. C-Style Strings in C++

A C-style string is a character array that ends with a special null character, written as '\0'.

The null character marks the end of the string.

Syntax

Example:

The array stores the characters:

The null character occupies one additional array position.

Example: Declare and Display a C-Style String

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    char name[] = "Hello C++";

    cout << name;

    return 0;
}

Output:

The compiler automatically calculates the required array size, including space for the terminating null character.

Important: Character Array vs Character

A single character uses the char data type:

A C-style string uses a character array:

Use single quotation marks for a character and double quotation marks for a string literal.

3. What Is std::string in C++?

std::string is a standard C++ library class used to store and manipulate text.

It is available through the <string> header.

Syntax

main.cpp
Run Online
#include <string>

std::string variable_name;

Example:

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Welcome to C++";

    cout << message;

    return 0;
}

Output:

Unlike a basic character array, a std::string can automatically manage its storage as the text changes.

Advantages of std::string

  • Easy declaration and initialization.

  • Automatically manages its character storage.

  • Supports concatenation using +.

  • Provides built-in functions for searching and modifying text.

  • Supports comparison using operators.

  • Can grow or shrink as needed.

For most general-purpose C++ programming, std::string is the recommended way to work with text.

4. Declaring and Initializing Strings

There are several ways to declare and initialize a string in C++.

Example 1: Declare an Empty String

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;

    cout << "Enter your name: ";
    cin >> name;

    cout << "Your name is " << name;

    return 0;
}

Sample input:

Output:

main.cpp
Run Online
Enter your name: Your name is Tanmoy

Example 2: Initialize a String Directly

Example 3: Initialize Using Another String

main.cpp
Run Online
string first = "Hello";
string second = first;

The value of first is copied into second.

Example 4: Initialize an Empty String

This creates an empty string.

Example 5: Use String Assignment

main.cpp
Run Online
string language;

language = "C++";

cout << language;

Output:

5. Taking String Input in C++

C++ provides cin and getline() to read string input.

The choice depends on whether you want to read one word or a complete line.

5.1 Using cin to Read a Single Word

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;

    cout << "Enter your name: ";
    cin >> name;

    cout << "Hello, " << name;

    return 0;
}

Sample input:

Output:

main.cpp
Run Online
Enter your name: Hello, Tanmoy

Why does this happen?

The extraction operator >> stops reading at whitespace. Therefore, it reads only the first word.

5.2 Using getline() to Read a Complete Line

Use getline() when you want to read a sentence or text containing spaces.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;

    cout << "Enter your full name: ";
    getline(cin, fullName);

    cout << "Your name is: " << fullName;

    return 0;
}

Sample input:

Output:

main.cpp
Run Online
Enter your full name: Your name is: Tanmoy Maity

The getline() function reads characters until it encounters a newline.

5.3 Using getline() After cin

A common beginner mistake happens when getline() is used immediately after cin >>.

Example of the problem:

main.cpp
Run Online
int age;
string name;

cin >> age;
getline(cin, name);

After reading the number, the newline character remains in the input stream. The next getline() may consume that newline and return an empty string.

Use cin.ignore() to discard the remaining characters through the next newline.

main.cpp
Run Online
#include <iostream>
#include <string>
#include <limits>
using namespace std;

int main() {
    int age;
    string name;

    cout << "Enter your age: ";
    cin >> age;

    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Enter your full name: ";
    getline(cin, name);

    cout << "Age: " << age << endl;
    cout << "Name: " << name;

    return 0;
}

Sample input:

Output:

main.cpp
Run Online
Enter your age: Enter your full name: Age: 35
Name: Tanmoy Maity

This is a reliable approach when reading a number followed by a complete line of text.

6. Finding the Length of a String

The length() and size() functions return the number of characters stored in a std::string.

Example

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Hello C++";

    cout << "Length: " << message.length() << endl;
    cout << "Size: " << message.size();

    return 0;
}

Output:

Both functions return the same value for std::string.

Spaces are included in the character count.

Note: For UTF-8 text, the returned size counts bytes, not necessarily user-perceived characters. A visible character may occupy multiple bytes.

7. Accessing Individual Characters in a String

You can access individual characters using an index.

String indexing starts at zero.

Example:

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string word = "Hello";

    cout << word[0] << endl;
    cout << word[1] << endl;
    cout << word[2] << endl;

    return 0;
}

Output:

You can also use the at() function.

main.cpp
Run Online
string word = "Hello";

cout << word.at(0);

Output:

The difference is that at() performs bounds checking and throws std::out_of_range when the index is invalid. Using an invalid index with operator[] is not safe.

8. Updating Characters in a String

You can modify a character by assigning a new value to a valid index.

Example

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string word = "Hello";

    word[0] = 'Y';

    cout << word;

    return 0;
}

Output:

The first character has been changed from H to Y.

9. Joining Strings Using Concatenation

Concatenation means joining two or more strings together.

C++ supports concatenation using the + and += operators.

Example 1: Using the + Operator

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Hello";
    string second = "World";

    string result = first + " " + second;

    cout << result;

    return 0;
}

Output:

Example 2: Using the += Operator

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Hello";

    message += " C++";

    cout << message;

    return 0;
}

Output:

The += operator appends additional text to the existing string.

10. Comparing Strings in C++

You can compare two std::string objects using comparison operators.

Common operators include:

OperatorMeaning
==Equal to
!=Not equal to
<Lexicographically less than
>Lexicographically greater than
<=Less than or equal to
>=Greater than or equal to

Example: Compare Two Strings

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Apple";
    string second = "Apple";

    if (first == second) {
        cout << "Strings are equal";
    } else {
        cout << "Strings are different";
    }

    return 0;
}

Output:

String comparisons are case-sensitive.

For example, "Apple" and "apple" are different strings.

The relational operators use lexicographical comparison based on character values. They do not perform dictionary-style language-aware sorting.

11. Searching for a Character or Word in a String

The find() function searches for a character or substring.

It returns the position of the first match. If no match is found, it returns string::npos.

Example: Search for a Word

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Welcome to C++ programming";

    size_t position = message.find("C++");

    if (position != string::npos) {
        cout << "Found at position: " << position;
    } else {
        cout << "Not found";
    }

    return 0;
}

Output:

Explanation:

  • find("C++") searches for the substring.

  • position stores the starting index.

  • string::npos indicates that the search did not find a match.

12. Extracting a Substring

The substr() function extracts part of a string.

Syntax

main.cpp
Run Online
string_name.substr(start_position, length);

Example

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Hello World";

    string result = message.substr(0, 5);

    cout << result;

    return 0;
}

Output:

Here:

  • 0 is the starting position.

  • 5 is the number of characters to extract.

If the requested length extends beyond the end of the string, substr() returns the available remaining characters.

13. Inserting and Removing Characters

C++ provides insert() and erase() to modify strings.

13.1 Using insert()

The insert() function adds characters at a specified position.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Hello World";

    message.insert(6, "C++ ");

    cout << message;

    return 0;
}

Output:

13.2 Using erase()

The erase() function removes characters from a string.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "Hello C++ World";

    message.erase(6, 4);

    cout << message;

    return 0;
}

Output:

The first argument specifies the starting position, and the second specifies the number of characters to remove.

14. Replacing Part of a String

The replace() function replaces a selected portion of a string with new text.

Example

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string message = "I like Java";

    message.replace(7, 4, "C++");

    cout << message;

    return 0;
}

Output:

Here, four characters starting at index 7 are replaced with "C++".

15. Converting Numbers and Strings

C++ provides functions to convert between numeric values and strings.

The <string> header provides commonly used conversion functions.

15.1 Convert a Number to a String

Use to_string().

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    int number = 100;

    string result = to_string(number);

    cout << result;

    return 0;
}

Output:

The result is a string, not an integer.

15.2 Convert a String to an Integer

Use stoi().

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "250";

    int number = stoi(text);

    cout << number + 50;

    return 0;
}

Output:

Other useful conversion functions include:

FunctionPurpose
stoi()Convert to int
stol()Convert to long
stoll()Convert to long long
stof()Convert to float
stod()Convert to double
to_string()Convert a numeric value to a string

These conversion functions can throw exceptions when the input is invalid or the value is outside the target type's range. For input validation, handle exceptions or consider alternatives such as std::from_chars where appropriate.

16. Useful String Functions in C++

The following table summarizes commonly used std::string operations.

Function or operatorPurposeExample
length()Returns string lengthtext.length()
size()Returns number of characters storedtext.size()
empty()Checks whether string is emptytext.empty()
clear()Removes all characterstext.clear()
append()Adds text to the endtext.append("Hi")
push_back()Adds one charactertext.push_back('A')
pop_back()Removes the last charactertext.pop_back()
find()Searches for texttext.find("C++")
substr()Extracts part of a stringtext.substr(0, 3)
insert()Inserts characterstext.insert(0, "Hi ")
erase()Removes characterstext.erase(0, 2)
replace()Replaces characterstext.replace(0, 2, "Hi")
compare()Compares stringstext.compare("Hello")
c_str()Provides a null-terminated character representationtext.c_str()

17. C-Style Strings vs std::string

Both approaches can store text, but they work differently.

FeatureC-Style Stringstd::string
RepresentationCharacter arrayStandard library class
HeaderNo special header for the type<string>
EndingUses '\0'Manages its own length
Size managementProgrammer manages array capacityManages storage automatically
ConcatenationFunctions such as strcat()+ or +=
ComparisonFunctions such as strcmp()==, !=, and other operators
SearchingFunctions such as strstr()find()
Ease of useRequires more manual handlingGenerally easier

For most modern C++ programs, prefer std::string. C-style strings remain useful when interacting with C libraries or APIs that require null-terminated character arrays.

18. Common Mistakes When Working With Strings

Mistake 1: Using cin When You Need a Complete Sentence

main.cpp
Run Online
string message;
cin >> message;

This reads only one word.

Use:

when you need to read a complete line.

Mistake 2: Forgetting the Null Character in a C-Style String

main.cpp
Run Online
char name[5] = {
  'H', 'e', 'l', 'l', 'o'
}
;

This array does not contain a terminating null character. It is not a valid null-terminated C-style string.

Use:

Mistake 3: Accessing a Character Outside the String

main.cpp
Run Online
string word = "Hello";

cout << word[10];

The index is outside the valid character range. Check the string length before accessing a character.

Mistake 4: Confusing Character and String Literals

main.cpp
Run Online
char letter = "A"; // Incorrect

Use:

A character uses single quotation marks. A string literal uses double quotation marks.

Mistake 5: Comparing Strings Incorrectly

For std::string, use:

main.cpp
Run Online
if (first == second) {
    cout << "Equal";
}

Do not use pointer comparison when you intend to compare the contents of C-style strings. Use strcmp() from <cstring> for that purpose.

Mistake 6: Ignoring Case Sensitivity

The strings "Hello" and "hello" are not equal using the ordinary comparison operators.

If you need case-insensitive matching, use an appropriate character-processing approach or a Unicode-aware library when handling international text.

19. Best Practices for Working With Strings in C++

  1. Prefer std::string for general text processing.

  2. Include the <string> header when using std::string.

  3. Use getline() to read complete lines.

  4. Use const std::string& when a function only needs to read a string and you want to avoid copying it.

  5. Check indexes before accessing characters.

  6. Use find() and check for string::npos when searching.

  7. Use empty() to check whether a string contains no characters.

  8. Be careful when mixing cin >> and getline().

  9. Handle exceptions when using numeric conversion functions.

  10. Use Unicode-aware tools when processing multilingual text that requires character-level operations.

20. Frequently Asked Questions (FAQs)

1. What is a string in C++?

A string is a sequence of characters used to represent text. C++ supports strings through character arrays and the std::string class.

2. What is std::string in C++?

std::string is a standard library class that provides convenient ways to store, access, compare, search, and modify text.

3. Which header file is required for strings in C++?

Include the <string> header to use std::string.

4. What is the difference between cin and getline()?

cin >> normally reads input until whitespace. getline() reads a complete line, including spaces, until it encounters a newline.

5. How do you find the length of a string?

Use length() or size():

main.cpp
Run Online
string name = "Tanmoy";

cout << name.length();

6. How do you join two strings in C++?

Use the + or += operator:

main.cpp
Run Online
string a = "Hello";
string b = "World";

string result = a + " " + b;

7. How do you compare two strings?

Use the comparison operators:

main.cpp
Run Online
if (first == second) {
    cout << "Equal";
}

8. How do you search for a word inside a string?

Use the find() function:

main.cpp
Run Online
string text = "Learn C++";

size_t position = text.find("C++");

Check whether the result equals string::npos to determine if the text was found.

9. Can a C++ string contain spaces?

Yes. A std::string can contain spaces, but you should use getline() when reading an entire line from standard input.

10. What is the difference between a C-style string and std::string?

A C-style string is a character array terminated by '\0'. std::string is a standard library class that manages its storage and provides built-in text operations.

11. Can we convert an integer into a string?

Yes. Use to_string():

main.cpp
Run Online
int number = 100;
string text = to_string(number);

12. Is std::string mutable in C++?

Yes. You can modify its characters, append text, insert characters, erase sections, and replace content.

Runnable Code Example: Strings in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <string>
#include <string_view>

void processStringView(std::string_view sv) {
    std::cout << "Viewing string slice: "" << sv << "" (Length: " << sv.length() << ")
";
}

int main() {
    std::string text = "OperateTools High Performance Engine";

    text.append(" - v2.0");
    std::cout << "Full String: " << text << "
";

    size_t pos = text.find("Performance");
    if (pos != std::string::npos) {
        std::cout << "'Performance' found at index: " << pos << "
";
    }

    // Zero-copy substring via string_view (C++17)
    std::string_view viewSlice(text.data() + 13, 11);
    processStringView(viewSlice);

    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is Small String Optimization (SSO) in std::string?

A: SSO is an optimization technique where `std::string` uses its internal stack storage buffer to hold short strings (usually up to 15-22 bytes) without triggering expensive heap memory allocations via `malloc`/`new`.
Q

Q: When should you use std::string_view instead of const std::string&?

A: Use `std::string_view` for read-only string parameters because it accepts `const char*` string literals, `std::string`, and substrings without allocating temporary `std::string` copies.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use std::string_view for read-only function parameters in C++17 and later.
2. Use text.reserve(N) before appending in loops to prevent multiple memory reallocations.
3. Check find() return values against std::string::npos before using positions.