Home Tutorials C++ Tutorial Strings
Strings

Strings


C++ Strings

Definition: In C++, a string is an object that represents a sequence of characters. Unlike a single char which holds only one letter or symbol, a string can store entire words, sentences, or paragraphs of text data.

Why: Strings are a core pillar of beginner C++ curricula because almost every modern application requires text manipulation—from taking a user's name to processing complex data logs. C++ provides a robust string class as part of its Standard Library that makes handling text much easier and safer than traditional character arrays.


Example: Basic String Operations

The following program demonstrates how to define a string and use built-in functions to analyze its properties:

#include <iostream>
#include <string> // Essential header for using the string class
using namespace std;

int main() {
    string greeting = "Hello";
    
    cout << greeting << endl;           // Outputs: Hello
    cout << greeting.length() << endl;  // Outputs: 5
    
    return 0;
}

Key String Functions & Mechanisms

  • Memory Management: One of the biggest advantages of the C++ string class is that it automatically manages memory. It grows or shrinks in size as you add or remove text, so you don't have to worry about defining a fixed length.
  • The .length() Function: This built-in function (also accessible as .size()) returns an integer representing the total number of characters currently stored in the string, including spaces and special symbols.
  • Concatenation: You can easily combine two strings using the + operator. For example: string fullName = firstName + " " + lastName;.
  • Accessing Characters: Even though a string is one object, you can access individual letters using square brackets [] and an index number. For example, greeting[0] would give you 'H'.

Common String Methods

Method Purpose
.append() Adds a string to the end of another string (alternative to +).
.clear() Deletes all characters from the string, making it empty.
.empty() Returns true if the string has a length of 0.
.substr(pos, len) Extracts a portion of the string starting at a specific position.

Key Notes

  • Header Requirement: While some compilers might include <string> automatically within <iostream>, it is best practice to always include #include <string> explicitly to ensure your code is portable across different systems.
  • Input Limitations: Remember that cin >> myString; only reads a single word. If you need to store a full sentence (like "Hello World"), you must use the getline(cin, myString); function.
  • Zero-Based Indexing: Like arrays, strings in C++ start counting at 0. The first character is at index 0, the second is at index 1, and the last character is at index length() - 1.

🏋️ Test Yourself With Exercises

Take our quiz on Strings to test your knowledge.

Browse Quizzes »