strings in cpp

9/13/2025

strings in cpp

Go Back

Strings in C++ Tutorial

Introduction

Strings in C++ are used to store and manipulate sequences of characters. C++ provides two main ways to work with strings:

  1. C-style strings (character arrays)

  2. std::string class (C++ strings)

Using std::string is the preferred and safer method in modern C++.


strings in cpp

C-Style Strings (Character Arrays)

C-style strings are arrays of characters terminated by a null character ('\0').

Example – C-Style String

#include <iostream>
using namespace std;

int main() {
    char name[20] = "Alice";

    cout << "Name: " << name << endl;
    return 0;
}

Output:

Name: Alice

Limitations:

  • Fixed size

  • Manual memory handling

  • Less secure compared to std::string


C++ Strings (std::string Class)

The std::string class (in <string> header) is part of the C++ Standard Library and makes working with strings much easier.

Key Features:

  • Dynamic size (auto resizes)

  • Rich set of built-in functions

  • Safer and more convenient than C-style strings

Example – Basic std::string

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

int main() {
    string name = "Alice";
    cout << "Name: " << name << endl;

    name += " Johnson";  // string concatenation
    cout << "Full Name: " << name << endl;

    cout << "Length: " << name.length() << endl;
    return 0;
}

Output:

Name: Alice
Full Name: Alice Johnson
Length: 13

Useful String Functions

FunctionDescription
length() / size()Returns number of characters
append(str)Appends a string
substr(pos, len)Returns substring
find(str)Finds the first occurrence
replace(pos, len, str)Replaces part of string
c_str()Returns C-style string

Example – String Functions

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

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

    cout << "Length: " << text.size() << endl;
    cout << "Substring: " << text.substr(0, 5) << endl;
    cout << "Find 'World': " << text.find("World") << endl;

    text.replace(6, 5, "C++");
    cout << "After replace: " << text << endl;

    return 0;
}

Output:

Length: 11
Substring: Hello
Find 'World': 6
After replace: Hello C++

Conclusion

Strings are essential for handling textual data in C++. While C-style strings are older and less safe, std::string provides powerful and flexible ways to work with strings.