C++ String Built-In Functions and How to Use Them

Formulas & functions · Updated November 22, 2026

C++ does not have a special set of built-in functions devoted to strings: its everyday string type is the standard-library class std::string, declared in <string>. Its member functions let you inspect, search, change, and convert text; include the header and use the relevant std::string operation, such as text.size() or text.find("cat").

What people mean by C++ string functions

The phrase “string built-in functions” is commonly used to ask how to work with text in C++. Strictly speaking, std::string is not a built-in language type like int. It is a class in the C++ standard library. The class provides member functions, while the language and standard library also provide operators and free functions that work with strings.

For ordinary text that can grow or shrink, std::string is usually the right starting point. It manages its own storage, knows its length, and offers operations such as append, erase, and find. A basic program needs #include <string>; stream input and output commonly also need #include <iostream>.

#include <iostream>
#include <string>

int main() {
    std::string name = "Mira";
    name += " Chen";
    std::cout << name << " has " << name.size() << " characters\n";
}

The result is Mira Chen has 9 characters. The examples below assume the standard std::string type unless they say otherwise.

Getting a string’s size and checking its contents

Several frequently used member functions answer basic questions about a string. size() returns its number of character elements, and length() returns the same value. They are equivalent for std::string; choose whichever name reads more clearly in your code. The return type is an unsigned size type, std::string::size_type.

  • empty() is true when the string contains no characters. It is generally clearer than comparing the size with zero.
  • size() and length() report the current number of elements, not the allocated storage.
  • capacity() reports how many elements can fit in the currently allocated storage before reallocation is needed. It is not the string’s length.

For example, if std::string word = "owl";, then word.size() is 3 and word.empty() is false. Calling clear() removes all characters, so the string becomes empty and its size becomes zero. Its capacity may remain available for later use; clearing does not promise to release the allocation.

Accessing characters safely

You can access individual elements with square brackets or with at(). For a string whose contents are "bird", text[0] is the first character, 'b'. C++ indexes from zero, so the last valid index is text.size() - 1 when the string is not empty.

at(index) checks the index and throws std::out_of_range if it is outside the string. In contrast, using operator[] with an index beyond the valid range is not a safe way to handle mistakes; validate the index first or use at() when a checked access is appropriate. front() and back() provide access to the first and last characters, but the string must not be empty when you call them.

These functions deal with character elements, not necessarily whole human-visible letters. With a UTF-8 string, one accented character or emoji can occupy multiple char elements. Consequently, size() measures encoded units for std::string, not Unicode code points or displayed characters. Unicode-aware counting or editing may require a dedicated library.

Adding, removing, and replacing text

Use += or append() to add text at the end. Use push_back(character) to add one character. For example, std::string label = "file"; label += ".txt"; produces file.txt. The append function has overloads for different sources and lengths, but concatenation with += is often easiest to read.

insert(position, text) adds characters at a position. erase(position, count) removes characters from that position, and replace(position, count, text) removes a range and puts new text in its place. These operations can shift later characters, so repeatedly inserting near the beginning of a very large string can be less efficient than assembling output another way.

To empty a string, call clear(). pop_back() removes its final character, but only call it when the string is nonempty. Functions such as erase and replace take positions and counts; check that those values match the intended range. An invalid starting position can cause std::out_of_range.

Finding, comparing, and extracting text

find(search_text) returns the position of the first match, or std::string::npos if no match exists. Because a valid position can be zero, do not treat the result as a simple true-or-false value. Compare it with npos:

std::string message = "red, green, blue";
auto comma = message.find(',');
if (comma != std::string::npos) {
    std::cout << "First comma at " << comma;
}

Here the first comma is at position 3. Related search functions include rfind for searching backward, and find_first_of or find_first_not_of for looking for characters from a set or outside that set. Their overloads allow you to specify a starting position.

substr(position, count) returns a new string containing a portion of the original. For instance, message.substr(5, 5) gives green. If the requested count runs past the end, the result is shortened to the available characters; if the starting position is greater than the string’s size, the function throws std::out_of_range.

Strings can be compared with operators such as ==, !=, and <. These compare character sequences according to the string’s comparison rules; they do not automatically ignore letter case or apply a language-specific sorting order. The member function compare() offers a more explicit comparison and returns a negative value, zero, or a positive value according to the ordering.

Converting between strings and numbers

Number conversion functions are related to string handling, but they are not all member functions of std::string. The standard library provides functions such as std::stoi to convert text to an integer and std::stod to convert text to a floating-point value. They are declared in <string> and used with the std:: prefix.

For the reverse direction, std::to_string(number) creates a string representation of a numeric value. These conversion functions can report errors: invalid input can cause std::invalid_argument, and a value outside the representable range can cause std::out_of_range. Parsing may also stop when it reaches a character that does not belong to the number, so validate the full input when accepting data that must contain only a number.

For more control over formatting and parsing, C++ streams such as std::ostringstream and std::istringstream are alternatives. Modern formatting facilities may also be available depending on the compiler and standard-library implementation. Pick a method based on whether you need simple conversion, strict input validation, or customized formatting.

String functions versus C-style strings

C++ also supports C-style strings: character arrays or pointers that conventionally end at a null character, '\0'. Functions such as std::strlen, std::strcmp, and std::strstr are declared in <cstring>. They are different from std::string member functions and operate under different assumptions.

A std::string stores its length and manages its memory. C-style functions generally need a valid null-terminated character sequence, and they do not know the size of the array that holds it. This makes raw buffer handling easier to get wrong. Prefer std::string for normal C++ text, but use C-style APIs when interacting with an interface that requires a character pointer or buffer.

c_str() provides a null-terminated character pointer for interfaces that expect one. The pointer is managed by the string and should not be treated as an independently owned buffer; changing the string can invalidate pointers or references to its contents. Also, a std::string can contain an embedded null character, while many C functions treat the first null as the end of the text. That difference matters when passing data across APIs.

Version-specific additions and practical choices

The core std::string operations are available across long-established C++ versions, but newer standards add conveniences. In C++20, starts_with() and ends_with() test prefixes and suffixes. In C++23, contains() tests whether a string contains a specified sequence or character. If code using these functions fails to compile, check both the selected language standard and whether the compiler’s standard library implements that version.

For many tasks, the choice is straightforward:

  • Use empty(), size(), and at() for basic checks and checked character access.
  • Use +=, append(), insert(), or replace() to build and edit text.
  • Use find() and substr() for straightforward searching and extraction.
  • Use std::string rather than a manually managed character array unless an interface or a specific constraint calls for the latter.

For repeated concatenation in a loop, a string can still be appropriate, but consider reserving an approximate capacity with reserve() if you know the likely final size and profiling shows allocation overhead matters. reserve() changes capacity, not the string’s logical length. Do not assume shrink_to_fit() must release memory: it is a request, not a guaranteed command.

Frequently Asked Questions

Is string a built-in data type in C++?
No. std::string is a standard-library class, usually used by including <string>. C++ also has character types and string literals, but those are not the same thing as the resizable std::string class.

What is the difference between size() and length()?
For std::string, they return the same number. Both count character elements in the string; neither necessarily counts displayed Unicode characters.

How do I check whether a string contains a word?
Use find() and compare the result with std::string::npos. In C++23, contains() is a more direct option when supported by the compiler and library.

How do I get one character from a string?
Use text[index] after ensuring the index is valid, or use text.at(index) for a bounds-checked access that throws if the index is invalid. The first character is at index zero.

Should I use std::string or a character array?
Use std::string for most ordinary text because it manages storage and provides convenient operations. Use a character array or pointer when required by a C API, a fixed-size data format, or a specific low-level constraint, and handle its bounds and null termination carefully.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.