Paramclasses Academy - Blog

Tutorials Details

What is Strings in C++

What is Strings in C++

October 15, 2026

A string is a sequence of characters used to represent text, such as a name, sentence, password, or message. In C++, you can work with text using character arrays and the std::string class.

In this module, we’ll focus on std::string, which is generally the more convenient and safer choice for everyday text processing.

Learning objectives

By the end of this module, you should be able to:

  • Understand character arrays and std::string.

  • Declare, initialize, and display strings.

  • Read a single word or a complete line of text.

  • Use common string operations and member functions.

  • Join, compare, search, and modify strings.

  • Process text using loops and conditions.

  • Build practical string-processing programs.

    Estimated time: 60–90 minutes

    Prerequisites: Modules 1–6, especially variables, loops, and arrays

1. What is a string?

A string represents text made up of characters. For example:

string name = "Param Classes";
string city = "Raipur";
string message = "Welcome to C++!";

In modern C++, the standard string class is named std::string. It is provided by the <string> header.

Two ways to represent text

Character array

char name[20] = "Param";

A fixed-size array of characters. C-style strings end with a null character '\0'.

std::string

#include <string>

std::string name = "Param";

A standard library class with convenient text operations and automatic memory management.

For most beginner C++ programs, prefer std::string unless you specifically need to learn or use C-style strings.

2. Declaring and initializing strings

To use std::string, include the <string> header.

Example 1: Basic string

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

int main() {
    string name = "Param Classes";

    cout << name;

    return 0;
}

Output

Param Classes

Example 2: Initialize an empty string

string message;

This creates an empty string. You can assign text to it later.

message = "Hello, C++!";

Example 3: Change a string

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

int main() {
    string language = "Java";

    language = "C++";

    cout << language;

    return 0;
}

Output

C++

Unlike a fixed-size character array, a std::string can grow or shrink as its contents change.

3. Reading string input: cin vs getline()

One of the most important string concepts is understanding how to read text containing spaces.

Example 1: Read a single word with cin

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

int main() {
    string name;

    cout << "Enter your name: ";
    cin >> name;

    cout << "Hello, " << name;

    return 0;
}

Example run

Enter your name: Rahul Sharma
Hello, Rahul

The extraction operator >> reads input until it encounters whitespace. Therefore, it reads only Rahul in this example.

Example 2: Read a complete line with getline()

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

int main() {
    string fullName;

    cout << "Enter your full name: ";
    getline(cin, fullName);

    cout << "Hello, " << fullName;

    return 0;
}

Example run

Enter your full name: Rahul Sharma
Hello, Rahul Sharma

getline(cin, fullName) reads the entire line, including spaces, up to the newline character.

Example 3: Common cin and getline() issue

Consider this program:

int age;
string name;

cin >> age;
getline(cin, name);

After cin >> age, the newline remaining in the input stream can cause getline() to read an empty line immediately.

Correct solution

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

int main() {
    int age;
    string name;

    cout << "Enter age: ";
    cin >> age;

    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Enter full name: ";
    getline(cin, name);

    cout << name << " is " << age << " years old.";

    return 0;
}

Example run

Enter age: 20
Enter full name: Rahul Sharma
Rahul Sharma is 20 years old.

The cin.ignore(...) statement discards the remainder of the current input line, including its newline. This is useful when switching from formatted input to getline().

4. Finding the length of a string

Use .length() or .size() to find how many char elements a std::string contains.

Example

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

int main() {
    string text = "Hello";

    cout << "Length = " << text.length() << endl;
    cout << "Size = " << text.size();

    return 0;
}

Output

Length = 5
Size = 5

Both functions return the same value for a std::string.

Important: For ordinary ASCII text, the length corresponds to the number of visible characters. For UTF-8 text containing characters such as many accented letters or emojis, the number of bytes, code points, and user-perceived characters can differ.

5. Accessing individual characters

You can access individual characters using an index, just as you do with arrays. String indexing also starts at zero.

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

int main() {
    string word = "HELLO";

    cout << word[0] << endl;
    cout << word[1] << endl;
    cout << word[4] << endl;

    return 0;
}

Output

H
E
O

The valid indices for "HELLO" are 0 through 4.

Modify a character

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

int main() {
    string word = "cat";

    word[0] = 'b';

    cout << word;

    return 0;
}

Output

bat

Use single quotes for an individual character such as 'b' and double quotes for a string such as "bat".

For checked access, .at(index) throws std::out_of_range if the index is invalid, whereas operator[] requires you to ensure the index is valid.

6. Concatenating strings

Concatenation means joining strings together. The + operator can concatenate strings, and += can append text to an existing string.

Example 1: Join two strings

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

int main() {
    string first = "Param";
    string second = "Classes";

    string full = first + " " + second;

    cout << full;

    return 0;
}

Output

Param Classes

Example 2: Append text with +=

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

int main() {
    string message = "Hello";

    message += " ";
    message += "World";

    cout << message;

    return 0;
}

Output

Hello World

Example 3: Append a character

string code = "C";
code += '+';
code += '+';

The value of code becomes "C++".

7. Important std::string functions

These member functions are frequently used in beginner and intermediate C++ programs.

Function

Purpose

Example

.length()

Returns string length

text.length()

.size()

Returns string size

text.size()

.empty()

Checks if string is empty

text.empty()

.append()

Appends text

text.append("!")

.substr()

Extracts part of a string

text.substr(0, 3)

.find()

Searches for text or a character

text.find("cat")

.replace()

Replaces part of a string

text.replace(0, 3, "Hi")

.erase()

Removes part of a string

text.erase(0, 2)

.insert()

Inserts text at a position

text.insert(0, "Hi ")

.clear()

Removes all characters

text.clear()

Example 1: empty() and clear()

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

int main() {
    string text = "Hello";

    cout << boolalpha << text.empty() << endl;

    text.clear();

    cout << text.empty();

    return 0;
}

Output

false
true

boolalpha prints Boolean values as true or false instead of 1 or 0.

Example 2: Extract a substring

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

int main() {
    string text = "Programming";

    cout << text.substr(0, 7);

    return 0;
}

Output

Program

The first argument is the starting index, and the second is the number of characters to extract.

Example 3: Find a substring

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

int main() {
    string text = "I love C++ programming";

    size_t position = text.find("C++");

    if (position != string::npos) {
        cout << "Found at index " << position;
    } else {
        cout << "Not found";
    }

    return 0;
}

Output

Found at index 7

find() returns the starting index of the first match. If no match exists, it returns string::npos, a special value representing “not found.”

Example 4: Replace text

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

int main() {
    string text = "I like Java";

    text.replace(7, 4, "C++");

    cout << text;

    return 0;
}

Output

I like C++

The call replace(7, 4, "C++") replaces four characters beginning at index 7 with "C++".

Example 5: Erase and insert

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

int main() {
    string text = "Hello World";

    text.erase(5, 6);
    cout << text << endl;

    text.insert(5, " C++");
    cout << text;

    return 0;
}

Output

Hello
Hello C++

erase(position, count) removes characters, while insert(position, text) inserts text at the given position.

8. Comparing strings

C++ strings can be compared using operators such as ==, !=, <, and >.

Example 1: Check whether two strings are equal

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

int main() {
    string password = "hello123";
    string entered = "hello123";

    if (password == entered) {
        cout << "Strings match";
    } else {
        cout << "Strings do not match";
    }

    return 0;
}

Output

Strings match

Example 2: Lexicographical comparison

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

int main() {
    string a = "apple";
    string b = "banana";

    if (a < b) {
        cout << "apple comes before banana";
    }

    return 0;
}

Output

apple comes before banana

String comparisons are case-sensitive and use lexicographical ordering based on character values. For example, "Hello" and "hello" are not equal.

9. Looping through a string

Loops let you process every character in a string.

Example 1: Print each character on a new line

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

int main() {
    string word = "CODE";

    for (size_t i = 0; i < word.length(); i++) {
        cout << word[i] << endl;
    }

    return 0;
}

Output

C
O
D
E

Example 2: Count vowels

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

int main() {
    string text = "education";
    int vowels = 0;

    for (char ch : text) {
        if (ch == 'a' || ch == 'e' || ch == 'i' ||
            ch == 'o' || ch == 'u' ||
            ch == 'A' || ch == 'E' || ch == 'I' ||
            ch == 'O' || ch == 'U') {
            vowels++;
        }
    }

    cout << "Vowels = " << vowels;

    return 0;
}

Output

Vowels = 5

The range-based loop visits each character. The condition checks whether that character is one of the five English vowels in either lowercase or uppercase.

Example 3: Reverse a string

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

int main() {
    string text = "hello";

    for (int i = static_cast<int>(text.length()) - 1;
         i >= 0; i--) {
        cout << text[i];
    }

    return 0;
}

Output

olleh

This example works for the given short ASCII string. For more general code, be careful when converting string lengths to int, because a very large string may exceed the range of int.

10. Character arrays and C-style strings

Before std::string became the usual choice for text processing, C and C++ programs often used arrays of characters.

A C-style string is a character sequence terminated by the null character '\0'.

Example

#include <iostream>
using namespace std;

int main() {
    char name[] = "Param";

    cout << name;

    return 0;
}

Output

Param

The array contains six characters in storage: P, a, r, a, m, and the terminating '\0'.

char vs std::string

Feature

char[] C-style string

std::string

Size

Fixed array capacity

Can grow and shrink

Termination

Uses '\0'

Manages its own length

Concatenation

Requires functions or manual logic

Supports + and +=

Input

Can use stream input with care

Convenient with cin and getline()

Memory handling

More manual

Managed by the class

Typical beginner choice

Useful for learning C-style strings

Recommended for everyday text

Important: Do not confuse the null character '\0' used to terminate a C-style string with the digit character '0'. They are different characters.

11. Converting a string to uppercase or lowercase

The C++ character-handling functions toupper() and tolower() are declared in <cctype>.

Example: Convert to uppercase

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

int main() {
    string text = "hello c++";

    for (char &ch : text) {
        ch = static_cast<char>(
            toupper(static_cast<unsigned char>(ch))
        );
    }

    cout << text;

    return 0;
}

Output

HELLO C++

The reference char &ch allows the program to modify each character in the original string. Converting through unsigned char avoids passing a negative plain-char value to the character-handling function.

These functions are suitable for basic character conversion in the current C locale. They do not provide full Unicode case conversion for all languages.

12. Mini project — Word and text analyzer

Build a program that accepts a complete line of text and calculates its length, counts spaces and vowels, and reports whether the text contains the word "C++".

Complete code

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

int main() {
    string text;
    int vowels = 0;
    int spaces = 0;

    cout << "Enter a line of text: ";
    getline(cin, text);

    for (char ch : text) {
        if (ch == 'a' || ch == 'e' || ch == 'i' ||
            ch == 'o' || ch == 'u' ||
            ch == 'A' || ch == 'E' || ch == 'I' ||
            ch == 'O' || ch == 'U') {
            vowels++;
        }

        if (ch == ' ') {
            spaces++;
        }
    }

    cout << "Length = " << text.length() << endl;
    cout << "Vowels = " << vowels << endl;
    cout << "Spaces = " << spaces << endl;

    if (text.find("C++") != string::npos) {
        cout << "Contains C++";
    } else {
        cout << "Does not contain C++";
    }

    return 0;
}

Example run

Enter a line of text: I love C++ programming
Length = 22
Vowels = 6
Spaces = 3
Contains C++

Concepts used

  • getline() reads a complete line, including spaces.

  • .length() calculates the number of char elements.

  • A range-based loop visits each character.

  • Conditions count vowels and spaces.

  • .find() searches for a substring.

The length here is the number of bytes stored in the ordinary string representation for this ASCII example. UTF-8 text may require more advanced Unicode-aware processing to count visible characters correctly.

13. Common mistakes when working with strings

Mistake 1: Forgetting the <string> header

Include #include <string> when using std::string.

Mistake 2: Using cin for a full sentence

cin >> text stops at whitespace. Use getline(cin, text) when you need the entire line.

Mistake 3: Using the wrong quotation marks

'A' is a character literal; "A" is a string literal. They are not interchangeable in every context.

Mistake 4: Accessing an invalid index

For a string of length 5, the valid character indices are 0 through 4. Check the index before accessing a character.

Mistake 5: Ignoring case sensitivity

"hello" == "Hello" evaluates to false. Convert the text appropriately if case-insensitive comparison is required.

14. Hands-on exercises

Try these problems independently before moving to the quiz.

Exercise 1 · Easy

Count the characters

Ask the user to enter a line of text and print its length.

Hint: Use getline() and .length().

Exercise 2 · Easy

Count vowels and consonants

Read a line and count its English vowels and consonants. Ignore spaces, digits, and punctuation.

Exercise 3 · Easy

Reverse a string

Input Param and output maraP.

Exercise 4 · Intermediate

Check for a palindrome

Determine whether a word reads the same forward and backward.

Examples: level is a palindrome; hello is not. Decide how your program should treat uppercase and lowercase letters.

Exercise 5 · Intermediate

Count a particular character

Ask for a sentence and a character, then count how many times that character appears.

Exercise 6 · Challenge

Remove extra spaces

Transform a sentence so that repeated spaces between words become a single space, with no leading or trailing spaces.

15. Interactive knowledge-check quiz

Select an answer for every question, then submit to check your score.

Strings quiz

0 / 7 answered

1. Which header provides std::string?

<iostream>

<string>

<cstring> only

<array>

2. What does cin >> text normally read?

The entire paragraph

Only up to the next whitespace

Only the first character

The whole input stream

3. Which function reads a complete line including spaces?

cin >> text

text.length()

getline(cin, text)

text.find()

4. What is the length of string text = "Hello"?

4

5

6

It is undefined

5. What does text.find("cat") return if the substring is not found?

0

-1 as an int in every case

string::npos

text.length() always

6. Which operator can concatenate two std::string objects?

%

&&

+

!

7. Why is std::string usually easier than a C-style character array?

It never uses memory

It automatically manages its text storage and offers convenient operations

It always stores Unicode graphemes

It cannot be modified

Submit quiz

Answer all seven questions before submitting.

16. Module 7 completion checklist

Your learning progress

0 / 7

I can declare and initialize std::string variables.

I understand cin versus getline().

I can access characters and concatenate strings.

I can use length, substr, find, replace, and erase.

I can compare strings and process them with loops.

I understand the difference between char arrays and std::string.

I have attempted the exercises, mini project, and quiz.