Strings hold almost every piece of text in C++—user names, file paths, command-line arguments, and log messages. This guide teaches how to create strings with std::string, understand C-style char arrays, join text, measure length, search substrings, and use essential <cstring> helpers.
01
String Basics
Text in C++.
02
Two Styles
std::string vs char*.
03
Concatenation
Join with +
04
Length & Compare
length, strlen, strcmp.
05
Search
find() and strchr().
06
Function Index
15 full tutorials.
Fundamentals
Definition and Usage
In C++, a string is a sequence of characters used to store and manipulate text. The modern approach uses the std::string class from <string>—an object that manages its own memory and provides member methods like length(), find(), and substr().
C++ also inherits C-style strings: null-terminated char arrays manipulated with functions from <cstring>—such as strlen(), strcmp(), and strcpy(). You will see both styles in textbooks, interviews, and code that talks to C libraries.
💡
Beginner Tip
Start with std::string for everyday programs. When a function expects const char*, pass myString.c_str(). Never use strcpy() without knowing the destination buffer size—buffer overflows are a common beginner mistake.
Foundation
📝 Syntax
C++ offers two main ways to work with strings:
C++
#include <string> // std::string
#include <cstring> // strlen, strcmp, strcpy, ...
std::string modern = "Hello, C++!";
std::string joined = first + " " + last;
size_t len = modern.length();
size_t pos = modern.find("C++");
char cStyle[] = "Hello";
size_t cLen = strlen(cStyle);
int cmp = strcmp(cStyle, "Hello");
Creating Strings
std::string literals — std::string text = "Hello"; the recommended modern form.
Work through these five examples from basic std::string creation to C-style helpers and substring search—patterns used in real C++ programs and interviews.
📚 Getting Started
Create your first strings and display them with std::cout.
Example 1 — Create and Display Strings
Assign text to std::string variables and print them—the foundation of every C++ program.
C++
#include <iostream>
#include <string>
int main() {
std::string language = "C++";
int version = 17;
std::cout << "Language: " << language << "\n";
std::cout << "Standard: C++" << version << "\n";
std::cout << "Ready to learn strings!\n";
return 0;
}
📤 Output:
Language: C++
Standard: C++17
Ready to learn strings!
How It Works
The stream operator << sends strings and numbers to std::cout. C++ converts the integer automatically when printing next to text. Include <string> whenever you use std::string.
Example 2 — std::string vs C-Style Strings
See both modern and classic string forms side by side, including escape sequences.
std::string: She said, "Hello!"
char array: C:\Users\Dev\project
modern length: 16
cStyle length: 20
How It Works
Both forms store text, but std::string is an object with methods while char cStyle[] is a fixed array ending in a null terminator '\0'. Use \" for quotes and \\ for backslashes inside string literals.
📈 Practical Patterns
Concatenation, inspection, comparison, and search.
Example 3 — Concatenation with + and +=
Build messages by joining std::string values with + and append with +=.
C++
#include <iostream>
#include <string>
int main() {
std::string first = "Hello";
std::string last = "C++";
std::string greeting = first + ", " + last + "!";
std::cout << greeting << "\n";
std::string status = "Status: ";
status += "Active";
std::cout << status << "\n";
return 0;
}
📤 Output:
Hello, C++!
Status: Active
How It Works
The + operator creates a new std::string without modifying the originals. The += operator appends in place—handy when building log lines or paths step by step. For many joins inside a loop, consider std::ostringstream or reserving capacity first.
Example 4 — Length, Equality, and strcmp()
Measure string size and compare text with == for std::string and strcmp() for C-strings.
Length: 5
First char: H
Last char: o
std::string == : 1
strcmp() == 0: 1
How It Works
word[0] accesses the first character with zero-based indexing. For std::string, use == to compare content. For C-strings, strcmp() returns 0 when they match—never write if (strcmp(a, b)) when you mean “are equal.”
Example 5 — Search with find() and strchr()
Locate substrings in std::string and find characters in C-strings—two essential search patterns.
URL contains /cpp at index 24
Extension starts at: 4
Extension: .cpp
How It Works
find() returns the index of the first match or std::string::npos when not found—always compare with npos. strchr() returns a pointer to the first matching character or nullptr. See our full tutorials on find() and strchr() for deeper coverage.
Applications
🚀 Common Use Cases
Console I/O — read user input with std::cin and display messages with std::cout.
File paths — build and inspect paths; search for extensions with find() or strrchr().
Validation — compare passwords or tokens with == (std::string) or strcmp() (C-strings).
Parsing — split tokens using find(), strspn(), and strcspn().
C library interop — pass myString.c_str() to functions expecting const char*.
Interview practice — reverse strings, count vowels, and check palindromes using both string styles.
🧠 How C++ Strings Work
1
You create a string
Write a std::string literal, read input from the user, or fill a char buffer from a file or network.
Create
2
C++ stores characters in memory
std::string manages a dynamic buffer. C-strings store bytes in an array ending with '\0'.
Storage
3
Methods or cstring functions transform
Call find(), +, strlen(), strcmp(), and other helpers to analyze or change text.
Transform
=
💬
Output or next step
Print to the console, write to a file, return from a function, or pass to another part of your program.
Important
📝 Notes
Include <string> for std::string and <cstring> for C-style functions—not the deprecated C header <string.h> in new C++ code.
strcmp() returns a signed integer, not a boolean—check == 0 for equality.
C functions like strcpy() and strcat() do not check buffer sizes—ensure the destination is large enough.
std::string::npos is the “not found” value from find()—compare explicitly instead of using the index as a boolean.
Use .c_str() to obtain a const char* for C APIs; the pointer is valid only while the std::string object is unchanged.
Character indexing with s[i] does not bounds-check in release builds—validate indices or use at(i) for safety.
Wrap Up
Conclusion
Strings are the backbone of C++ text handling. Master std::string creation, concatenation, and find(), then learn the essential <cstring> toolkit—strlen(), strcmp(), and strcpy()—and you are ready to write real programs and tackle interview questions.
Practice the examples on this page, then explore the full String Functions index for in-depth tutorials on every function in our series.
Check find() != std::string::npos before using an index
Write strcmp(a, b) == 0 for C-string equality
Use strncpy() / strncat() when length limits matter
❌ Don’t
Call strlen() on a std::string object directly
Use strcpy() without knowing the destination size
Treat strcmp() return value as true/false for equality
Mix <string.h> and <cstring> inconsistently
Store pointers from c_str() after the string is modified
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about C++ strings
Use these points as you write your first C++ programs.
5
Core concepts
💬01
Two Styles
std::string and char*.
Basics
📝02
Headers
<string> and <cstring>.
Syntax
🔗03
Join with +
Concatenate strings.
Operator
🛠04
Compare Safely
== or strcmp == 0.
Methods
📚05
Function Index
15 full tutorials.
Next step
❓ Frequently Asked Questions
A string is a sequence of characters used to store and manipulate text. In modern C++ you usually use the std::string class from <string>. C-style strings are null-terminated char arrays handled with functions from <cstring> such as strlen() and strcmp(). Both styles appear in real programs and interviews.
Prefer std::string for new code—it manages memory automatically, supports + concatenation, and provides methods like find() and length(). Use char arrays and <cstring> when working with C APIs, fixed buffers, or legacy code. Learn both because technical interviews often test cstring functions.
With std::string, use the + operator or += : std::string full = first + " " + last; label += " more";. For C-style strings, use strcat() or strncat() from <cstring>, making sure the destination buffer is large enough.
text.length() (or text.size()) is a std::string member that returns the number of characters in the object. strlen(ptr) is a C function that counts characters in a null-terminated char array until it reaches '\0'. Do not call strlen() on a std::string directly—use length() or convert with c_str() only when a C API requires it.
For std::string, use == and != for equality, or compare() for ordering. For C-strings, use strcmp(a, b)—it returns 0 when strings match. Never assume strcmp returns true/false; check for zero explicitly: if (strcmp(a, b) == 0).
Learn std::string creation, output with cout, concatenation, and find() on this page. Then open the String Functions index for full tutorials on find(), strlen(), strcpy(), strcmp(), and every essential <cstring> helper in our series.
Did you know?
C++ has supported std::string since the 1998 standard, but C-style char* strings came from C and remain in the language today. That is why you will see both text.find("hello") in modern code and strlen(buffer) in older libraries—knowing both styles makes you a stronger C++ programmer.