Strings in C++

In this tutorial, you will learn about Strings in C++. You will explore their declaration, manipulation, and key functions. You will also see how to handle strings in different ways. The tutorial covers the differences between C-style strings and std::string. Real-world examples will help you understand the concept better.

Contents:

  1. What are Strings in C++?
  2. C-style Strings (Character Arrays) in C++
  3. Using the std::string Class in C++
  4. Character Arrays Vs std::string in C++
  5. Common String Operations in C++
  6. String Concatenation in C++
  7. Examples of String Operations in C++
  8. String Functions in C++
  9. String Iteration in C++
  10. C++ String Manipulation
  11. Converting Strings to Other Data Types in C++
  12. FAQs on Strings in C++

What are Strings in C++?

In C++, strings are used to store and work with text. A string is simply a sequence of characters, ending with a special character called the null terminator (\0). This character tells the computer where the string stops.

C++ provides two main ways to handle strings:

  • C-style Strings (Character Arrays)
  • std::string Class (from the Standard Library)

C-style Strings (Character Arrays) in C++

A C-style string is an array of characters ending with a null character (\0), which marks the end of the string.

advertisement

Syntax of C-style Strings

char strName[size];       // Declaration of character array
char strName[] = "Hello"; // Initialization with string literal
char strName[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Manual null-terminated string

Example:

#include <iostream>
using namespace std;
 
int main()
{
    char course[] = "Sanfoundry";  // Automatically adds '\0'
    cout << "Course: " << course << endl;
    return 0;
}

Output:

👉 Apply Now for Free C Certification - December 2025
Course: Sanfoundry

Example 2: Taking Input with cin

#include <iostream>
using namespace std;
 
int main()
{
    char subject[20];
    cout << "Enter subject: ";
    cin >> subject;  // Reads until space
    cout << "Subject: " << subject << endl;
    return 0;
}

Output:

advertisement
Enter subject: C++
Subject: C++

Using the std::string Class in C++

The std::string class in C++ is part of the Standard Library (<string> header) and provides a more flexible and safer way to handle strings than C-style character arrays.

Syntax:

#include <string>
using namespace std;
 
// Declaration
string str_name;
 
// Initialization
string str_name = "Sanfoundry";

Example 1: Basic Declaration and Initialization

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    // Initialize string
    string course = "Sanfoundry C++ Course"; 
    cout << "Course: " << course << endl;
    return 0;
}

Output:

Course: Sanfoundry C++ Course

Example 2: Using getline() to Read Full Input

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string courseName;
    cout << "Enter full course name: ";
    getline(cin, courseName);
    cout << "Full Course Name: " << courseName << endl;
    return 0;
}

Output:

Enter full course name: Sanfoundry Advanced C++ Course
Full Course Name: Sanfoundry Advanced C++ Course

Character Arrays Vs std::string in C++

Here is the comparison of Character Arrays and std::string in C++

Feature Character Arrays (char[]) std::string (C++ Standard Library)
Definition Array of characters ending with \0. A flexible string class with built-in functions.
Header File <cstring> <string>
Size Handling Fixed size (must predefine maximum size). Dynamically resizable.
Null Terminator (\0) Required at the end to mark termination. Managed automatically.
Ease of Use Requires manual operations for modification. Provides built-in functions like length(), append(), find(), etc.
Memory Management Needs manual handling for dynamic allocation. Handled automatically.
Concatenation Done using strcat(). Done using + or append().
Comparison Uses strcmp(). Can use ==, <, >, etc., directly.
Performance Faster for small, fixed-size strings. More flexible and safer

Common String Operations in C++

In C++, strings are a fundamental part of programming, and the Standard Library provides various operations to manipulate them efficiently. Below are some common string operations in C++:

Operation Description Example
length() / size() Returns the number of characters in a string. s.length(); or s.size();
empty() Checks if the string is empty. s.empty();
clear() Erases all characters in the string. s.clear();
append(str) / += Adds another string to the end. s.append(” World”); or s += ” World”;
insert(pos, str) Inserts a string at a specific position. s.insert(5, “C++ “);
erase(pos, len) Removes characters from a given position. s.erase(3, 2);
replace(pos, len, str) Replaces part of the string with another. s.replace(0, 4, “Hello”);
substr(pos, len) Extracts a substring. s.substr(2, 5);
find(str) Finds the first occurrence of a substring. s.find(“lo”);
rfind(str) Finds the last occurrence of a substring. s.rfind(“lo”);
compare(str) Compares two strings (returns 0 if equal). s1.compare(s2);
c_str() Converts std::string to a C-style string. s.c_str();
push_back(ch) Appends a character to the end. s.push_back(‘!’);
pop_back() Removes the last character. s.pop_back();
toupper(ch) / tolower(ch) Converts a character to uppercase/lowercase. toupper(‘a’); or tolower(‘A’);

String Concatenation in C++

String concatenation in C++ combines or joins two or more strings into a single string. This can be done using:

  • The + operator
  • The += operator
  • The append() function

1. Using the + Operator

The + operator concatenates two strings and returns a new string.

Syntax:

string str3 = str1 + str2;

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course1 = "C++ ";
    string course2 = "Internship";
 
    // Concatenation using +
    string result = course1 + course2;
    cout << "Combined String: " << result << endl;
 
    return 0;
}

Output:

Combined String: C++ Internship

This C++ program combines two strings using the + operator. It stores two text values in separate string variables, joins them into one, and prints the result. This shows how to merge strings easily in C++.

2. Using the += Operator

The += operator appends the content of one string to another.

Syntax:

str1 += str2;

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course1 = "Sanfoundry ";
    string course2 = "Internship";
 
    // Concatenation using +=
    course1 += course2;
    cout << "After appending: " << course1 << endl;
 
    return 0;
}

Output:

After appending: Sanfoundry Internship

This C++ program appends one string to another using the += operator. It stores two text values in separate string variables, adds the second string to the first, and prints the result. This demonstrates a simple way to modify and combine strings in C++.

3. Using the append() Method

The append() method adds one string to the end of another.

Syntax:

str1.append(str2);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course1 = "C++ ";
    string course2 = "Certification";
 
    // Concatenation using append()
    course1.append(course2);
    cout << "After append(): " << course1 << endl;
 
    return 0;
}

Output:

After append(): C++ Certification

This C++ program joins two strings using the append() function. It stores two text values in separate string variables, adds the second string to the first, and prints the result. This method is a simple way to combine strings without using the + operator.

Examples of String Operations in C++

1. Finding String Length

The length() or size() method returns the length of a string.

Syntax:

int len = str.length();

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string platform = "Sanfoundry";
 
    // Finding length of the string
    cout << "Length of the string: " << platform.length() << endl;
 
    return 0;
}

Output:

Length of the string: 10

2. String Comparison

The compare() function compares two strings and returns 0 if strings are equal.

Syntax:

int result = str1.compare(str2);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course1 = "C++";
    string course2 = "Python";
 
    // Comparing strings
    if (course1.compare(course2) == 0)
        cout << "Courses are the same." << endl;
    else
        cout << "Courses are different." << endl;
 
    return 0;
}

Output:

Courses are different.

3. Accessing and Modifying Characters

Individual characters in a string can be accessed or modified using [] or at().

Syntax:

char ch = str[index];
str[index] = 'A';

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "Sanfoundry";
 
    // Accessing character
    cout << "First character: " << course[0] << endl;
 
    // Modifying character
    course[0] = 's';
    cout << "Modified string: " << course << endl;
 
    return 0;
}

Output:

First character: S
Modified string: sanfoundry

4. Substring Extraction

The substr() method extracts a portion of the string.

Syntax:

string sub = str.substr(pos, len);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "Sanfoundry Internship";
 
    // Extracting substring
    string sub = course.substr(11, 9);
    cout << "Extracted String: " << sub << endl;
 
    return 0;
}

Output:

Extracted String: Internship

5. Reversing a String

Reversing a string means changing its order so that the last character becomes the first and vice versa.

Example:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
 
int main()
{
    string course = "Sanfoundry";
 
    // Reversing string using reverse()
    reverse(course.begin(), course.end());
    cout << "Reversed String: " << course << endl;
 
    return 0;
}

Output:

Reversed String: yrdnuofnaS

String Functions in C++

C++ provides various built-in string functions, such as:

  • length() / size() – Returns string length.
  • append() – Appends a string.
  • insert() – Inserts a string at a position.
  • erase() – Deletes characters from a string.
  • replace() – Replaces part of the string.
  • find() – Finds the position of a substring.
  • substr() – Extracts a substring.
  • compare() – Compares two strings.
  • clear() – Clears string content.
  • empty() – Checks if a string is empty.

1. Inserting and Erasing Substrings

insert() inserts a substring at a given position. erase() removes a substring from the string.

Syntax:

str.insert(pos, sub);
str.erase(pos, len);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "C++ Internship";
 
    // Inserting substring
    course.insert(3, " Sanfoundry");
    cout << "After Insertion: " << course << endl;
 
    // Erasing substring
    course.erase(3, 11);
    cout << "After Erasing: " << course << endl;
 
    return 0;
}

Output:

After Insertion: C++ Sanfoundry Internship
After Erasing: C++ Internship

2. replace()

The replace() method replaces part of a string with another substring.

Syntax:

str.replace(pos, len, new_sub);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "C++ Internship";
 
    // Replacing substring
    course.replace(4, 10, "Certification");
    cout << "After Replacement: " << course << endl;
 
    return 0;
}

Output:

After Replacement: C++ Certification

3. find()

The find() method searches for a substring and returns its position. It returns string::npos if not found.

Syntax:

int pos = str.find(sub);

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "C++ Internship";
 
    // Finding substring position
    size_t pos = course.find("Internship");
 
    if (pos != string::npos)
        cout << "Substring found at position: " << pos << endl;
    else
        cout << "Substring not found!" << endl;
 
    return 0;
}

Output:

Substring found at position: 4

4. clear()

Clears the content of a string.

Syntax:

str.clear();

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "Sanfoundry C++ Course";
    course.clear();
    cout << "After Clearing: " << course << endl;
    cout << "Length after clear: " << course.length() << endl;
 
    return 0;
}

Output:

After Clearing: 
Length after clear: 0

5. empty()

Checks whether the string is empty or not.

Syntax:

str.empty();

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "";
 
    if (course.empty())
        cout << "String is empty!" << endl;
    else
        cout << "String is not empty!" << endl;
 
    return 0;
}

Output:

String is empty!

String Iteration in C++

String iteration is the process of accessing each character in a string one by one.

1. Using for Loop

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string course = "Sanfoundry";
 
    // Iterating using for loop
    cout << "Characters in the string: ";
    for (int i = 0; i < course.length(); ++i) {
        cout << course[i] << " ";
    }
    cout << endl;
 
    return 0;
}

Output:

Characters in the string: S a n f o u n d r y

2. Using Range-Based for Loop

#include <iostream>
#include <string>
using namespace std;
 
int main(
{
    string subject = "C++";
 
    // Iterating using range-based for loop
    cout << "Characters in the subject: ";
    for (char ch : subject) {
        cout << ch << " ";
    }
    cout << endl;
 
    return 0;
}

Output:

Characters in the subject: C + +

3. Using Iterators

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string internship = "Internship";
 
    // Iterating using iterator
    cout << "Characters in internship: ";
    for (auto it = internship.begin(); it != internship.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
 
    return 0;
}

Output:

Characters in internship: I n t e r n s h i p

C++ String Manipulation

String manipulation refers to modifying strings by adding, removing, or altering characters.

1. Modifying Characters

#include <iostream>
using namespace std;
 
int main()
{
    string course = "Java";
    course[0] = 'C';  // Modify characters
    course[1] = '+';
    course[2] = '+';
    cout << course;  // Output: C++a
    return 0;
}

2. Converting to Uppercase and Lowercase

#include <iostream>
#include <algorithm>
using namespace std;
 
int main()
{
    string course = "Sanfoundry";
    transform(course.begin(), course.end(), course.begin(), ::toupper);
    cout << course << endl;  // Output: SANFOUNDRY
 
    transform(course.begin(), course.end(), course.begin(), ::tolower);
    cout << course;  // Output: sanfoundry
    return 0;
}

3. Removing Whitespaces

#include <iostream>
using namespace std;
 
int main()
{
    string course = "Sanfoundry  C++  Course", no_space = "";
    for (char ch : course)
    {
        if (ch != ' ')
            no_space += ch;
    }
    cout << no_space;  // Output: SanfoundryC++Course
    return 0;
}

4. Replacing Characters

#include <iostream>
using namespace std;
 
int main()
{
    string course = "C++ Basics";
    course.replace(0, 3, "Python");
    cout << course;  // Output: Python Basics
    return 0;
}

5. Removing Vowels

#include <iostream>
using namespace std;
 
int main()
{
    string course = "Sanfoundry", no_vowels = "";
    for (char ch : course)
    {
        if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u')
            no_vowels += ch;
    }
    cout << no_vowels;  // Output: Snfndry
    return 0;
}

Converting Strings to Other Data Types in C++

In C++, converting strings to other data types is a common task, especially when dealing with user input, file handling, and data processing.

1. Convert String to Integer (stoi)

#include <iostream>
using namespace std;
 
int main()
{
    string score = "95";
    int marks = stoi(score);  // Convert string to int
    cout << "Marks: " << marks + 5;  // Output: Marks: 100
    return 0;
}

2. Convert String to Float (stof)

#include <iostream>
using namespace std;
 
int main()
{
    string percentage = "88.75";
    float marks = stof(percentage);  // Convert string to float
    cout << "Percentage: " << marks + 1.25;  // Output: Percentage: 90
    return 0;
}

3. Convert String to Long (stol)

#include <iostream>
using namespace std;
 
int main()
{
    string distance = "123456";
    long value = stol(distance);  // Convert string to long
    cout << "Distance: " << value + 100;  // Output: Distance: 123556
    return 0;
}

4. Convert String to Double (stod)

#include <iostream>
using namespace std;
 
int main()
{
    string price = "199.99";
    double amount = stod(price);  // Convert string to double
    cout << "Total Price: " << amount + 50.01;  // Output: Total Price: 250
    return 0;
}

5. Convert Integer to String (to_string)

#include <iostream>
using namespace std;
 
int main()
{
    int sanfoundryId = 101;
    string id = to_string(sanfoundryId);  // Convert int to string
    cout << "Sanfoundry ID: " + id;  // Output: Sanfoundry ID: 101
    return 0;
}

6. Convert Float to String (to_string)

#include <iostream>
using namespace std;
 
int main()
{
    float price = 125.75;
    string cost = to_string(price);  // Convert float to string
    cout << "Final Price: " + cost;  // Output: Final Price: 125.750000
    return 0;
}

FAQs on Strings in C++

1. What is a string in C++?
A string in C++ is a sequence of characters. It can be represented using C-style character arrays or the std::string class from the Standard Library. The std::string class is preferred because it provides built-in functions for easier manipulation.

2. How do you declare and initialize a string in C++?
Strings can be initialized using the std::string class or a character array. The std::string class automatically manages memory, while character arrays require manual handling.

3. How do you concatenate (combine) two strings in C++?
Strings can be concatenated using the + operator or the append() method.

4. How do you extract a substring from a string in C++?
The substr() method is used to extract a portion of a string, given the starting index and length.

5. What is the difference between C-style strings and std::string?
C-style strings are character arrays that end with a null terminator (\0), whereas std::string is a dynamic and flexible class that provides built-in functions for string operations. std::string is safer and easier to use.

6. How do you find the length of a string in C++?
The std::string class provides the length() or size() method to determine the number of characters in a string. For C-style strings, the strlen() function is used.

7. How can you reverse a string in C++?
A string can be reversed using loops or by utilizing the reverse() function from the algorithm library.

Key Points to Remember

Here is the list of key points we need to remember about “Strings in C++”.

  • Strings in C++ can be represented using C-style character arrays (char[]) or the std::string class, with std::string being the preferred option due to its flexibility.
  • Strings can be initialized directly using double quotes, assigned new values, or manipulated dynamically without manual memory management.
  • Basic string operations include finding length (length()), concatenation (+ or append()), comparison (compare() or ==), and substring extraction (substr()).
  • String modification methods like insert(), erase(), and replace() allow adding, removing, or replacing characters or substrings efficiently.
  • The find() method helps locate a substring within a string, returning its position, while string::npos indicates that the substring was not found.
  • Iterating through a string can be done using loops (for, while, range-based for) or iterators for character-by-character processing.
  • String conversion functions like stoi(), stof(), and to_string() help convert strings to numbers and vice versa, simplifying data manipulation.
  • Unlike character arrays, std::string automatically manages memory, dynamically adjusting its size, reducing the risk of buffer overflow and memory leaks.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.