C++ Strings

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Basics

What You’ll Learn

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.

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.

📝 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 literalsstd::string text = "Hello"; the recommended modern form.
  • char arrayschar buf[] = "Hello"; fixed-size C-style strings ending with '\0'.
  • char* pointers — point to string literals or dynamically allocated memory; handle with care.

Essential Headers

#include <string>    // std::string, find(), length()
#include <cstring>   // strlen(), strcmp(), strcpy()
#include <iostream>  // std::cout for output

⚡ Quick Reference

Create
std::string s = "Hello, C++!";

std::string literal

Concatenate
std::string full = a + " " + b;

+ operator

Length
text.length()

std::string member

Compare C-strings
strcmp(a, b) == 0

Zero means equal

Examples Gallery

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;
}

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.

C++
#include <iostream>
#include <string>
#include <cstring>

int main() {
    std::string modern = "She said, \"Hello!\"";
    char cStyle[] = "C:\\Users\\Dev\\project";

    std::cout << "std::string: " << modern << "\n";
    std::cout << "char array:  " << cStyle << "\n";
    std::cout << "modern length: " << modern.length() << "\n";
    std::cout << "cStyle length: " << strlen(cStyle) << "\n";
    return 0;
}

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;
}

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.

C++
#include <iostream>
#include <string>
#include <cstring>

int main() {
    std::string word = "Hello";
    char copy[] = "Hello";

    std::cout << "Length: " << word.length() << "\n";
    std::cout << "First char: " << word[0] << "\n";
    std::cout << "Last char: " << word[word.length() - 1] << "\n";

    std::cout << "std::string == : "
              << (word == "Hello") << "\n";
    std::cout << "strcmp() == 0: "
              << (strcmp(copy, "Hello") == 0) << "\n";
    return 0;
}

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.”

🚀 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.

📝 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.

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.

💡 Best Practices

✅ Do

  • Prefer std::string for new C++ code
  • Use == to compare std::string content
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about C++ strings

Use these points as you write your first C++ programs.

5
Core concepts
📝 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.

Explore every string function

Open the function index for searchable guides with syntax, five examples, and FAQs for each function.

String Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful