HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Strings

Strings

std::string concatenation, length, substr and find.

Simple enough for a 5-year-old to understand

Concatenation and length

Example code
1
#include <iostream>
2
#include <string>
3
using namespace std;
4
int main() {
5
string s = "Hex";
6
s = s + "Library";
Concatenate with +.
CodeConcatenate with +.
7
cout << s << " " << s.length() << endl;
HexLibrary 10
Output / InputHexLibrary 10
8
return 0;
9
}
CodeOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Concatenate and print the texts "Hex" and "Library" using + (HexLibrary).

🎯 Expected output: HexLibrary

Loading editor…

About this topic

In C++, there is a string type for text, which is a fundamental departure from C's character array approach. The string knows its own length, grows its memory when needed, and releases its memory upon destruction.

This is an example of one of C++'s core principles: an object manages the resource, and when the object goes out of scope, the resource is freed. When processing text, you really have to go out of your way to cause a memory leak or a buffer overflow.

The point to watch out for when working with strings is encoding. The string counts bytes, not characters. Since Turkish letters take up two bytes in UTF-8, the length comes out greater than the number of letters, and iterating byte by byte splits the letters in half.

What you will learn

  • defining and concatenating strings
  • the length and size functions
  • the difference between at and square brackets
  • using substr and find
  • the relationship between string and char arrays

When to use?

When reading a line from the user, getline is used instead of the stream operator: the stream operator stops at whitespace and captures a two-word input only halfway.

If you are doing a lot of concatenation inside a loop, new memory might be allocated at each step; reserving space beforehand with reserve prevents this.

Common mistakes

Wrong

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

int main() {
    string name;
    cout << "Enter name: ";
    cin >> name;
    cout << "Hello " << name << endl;
    return 0;
}

The stream operator stops at the first whitespace. If the user types two words, only the first one is read, the second remains in the buffer and messes up the next read. To read a full line, getline is used.

Correct

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

int main() {
    string name;
    cout << "Enter name: ";
    getline(cin, name);
    cout << "Hello " << name << endl;
    return 0;
}

Wrong

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

int main() {
    string word = "abc";
    cout << word[10] << endl;
    return 0;
}

Square brackets do NOT perform boundary checking; reading outside the array is undefined behavior and usually prints garbage characters. The at function does the same job but throws an exception out of bounds. Having errors visible rather than remaining silent is preferred.

Correct

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

int main() {
    string word = "abc";
    if (word.size() > 10) {
        cout << word.at(10) << endl;
    } else {
        cout << "Too short" << endl;
    }
    return 0;
}

Wrong

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

int main() {
    string text = "hello world";
    int pos = text.find("none");
    if (pos > 0) {
        cout << "Found" << endl;
    }
    return 0;
}

If find cannot find it, it returns a very large special value, not minus one. Assigning this value to an int leads to overflow and comparisons yield wrong results. The correct check is to compare the return value with the string class's npos constant.

Correct

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

int main() {
    string text = "hello world";
    if (text.find("none") != string::npos) {
        cout << "Found" << endl;
    } else {
        cout << "Not found" << endl;
    }
    return 0;
}

Frequently asked questions

Is there a difference between length and size?

None at all, both return the same value. length exists because it feels natural in a text context, while size exists to be consistent with other containers. Using size in code working with container templates is more compatible.

Can I use equals for string comparison?

Yes, comparison operators are overloaded for the string type and compare the contents. This is one of the greatest conveniences carried over from C; in C, the same operation requires strcmp, and using equals compares addresses, failing silently.

Why do Turkish characters cause issues?

The string counts bytes. Since Turkish letters take up two bytes in UTF-8, the length comes out greater than the number of letters, and accessing by index splits the letter in half, producing corrupted output. Using English characters in code examples prevents this issue from the start.

Summary

The string manages its own memory; the risk of overflow and leaks is eliminated.

To read a full line, getline is used; the stream operator stops at whitespace.

at performs boundary checking, square brackets do not.

find returns npos when it fails to find; not minus one.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code