C++ Strings

In C++, a string is a sequence of characters used to store text. You can use either C-style strings (arrays of characters ending with a null character '\0') or the std::string class provided by the C++ Standard Library for easier manipulation.

C-Style Strings

#include <iostream>
using namespace std;

int main() {

    char name[10] = "Alice"; // C-style string
    cout << "Name: " << name << endl;

    return 0;
}

Output

Name: Alice

Using std::string

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

int main() {

    string name = "Alice"; // std::string
    cout << "Name: " << name << endl;

    return 0;
}

Output

Name: Alice

Common String Operations

  • Concatenation: Combine strings using the + operator.
  • Length: Get the length of a string using name.length() or name.size().
  • Access Characters: Use name[index] to access individual characters.
  • Comparison: Compare strings using ==, <, >, etc.

Example: String Operations

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

int main() {

    string firstName = "Alice";
    string lastName = "Smith";

    // Concatenation
    string fullName = firstName + " " + lastName;
    cout << "Full Name: " << fullName << endl;

    // Length
    cout << "Length of full name: " << fullName.length() << endl;

    // Access character
    cout << "First character: " << fullName[0] << endl;

    return 0;
}

Output

Full Name: Alice Smith
Length of full name: 11
First character: A

Important Notes

  • std::string is easier and safer to use than C-style strings.
  • Strings in C++ are mutable when using std::string, but C-style strings are arrays of characters.
  • Many useful string functions are available with std::string, such as substr(), find(), replace(), and c_str().

Next Topic

Next, learn about String Functions in C++.