codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

27 / 87 topics
25Arrays (1D and Multidimensional)26Passing Array to a Function27Strings & the C++ String Class
Tutorials/C++ Programming/Strings & the C++ String Class
⚡C++ Programming

Strings & the C++ String Class

Updated 2026-05-12
30 min read

Strings & the C++ String Class

In programming, strings are sequences of characters used to represent text. Understanding how to work with strings is crucial for any developer, as they are fundamental in tasks like user input handling, data processing, and output formatting. In this tutorial, we will explore two primary ways to handle strings in C++: C-style strings (character arrays) and the more modern and feature-rich std::string class from the Standard Template Library (STL). We'll cover string manipulation methods such as length, substr, find, replace, and append, as well as how to compare strings. Additionally, we'll learn how to read strings with spaces using getline.

Introduction

C++ provides two main ways to handle strings:

  1. C-style Strings: These are arrays of characters terminated by a null character ('\0'). They are similar to strings in other C-like languages.
  2. std::string Class: Part of the Standard Template Library (STL), this class offers a more user-friendly and safer way to handle strings, with numerous built-in methods for manipulation.

Understanding both approaches will help you choose the right tool for different scenarios, ensuring efficient and error-free code.

C-style Strings

What is a C-style String?

A C-style string is essentially an array of characters (char) where the last character is always the null character ('\0'). This indicates the end of the string. For example:

cstyle_string.cpp
1char str[] = "Hello, World!";

Here, str is an array containing 13 characters: 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', followed by the null character '\0'.

Operations on C-style Strings

C-style strings are manipulated using functions from the <cstring> library, such as:

  • strlen: Returns the length of a string.
  • strcpy: Copies one string to another.
  • strcat: Concatenates two strings.
  • strcmp: Compares two strings.

Example: Using C-style Strings

cstyle_operations.cpp
1#include <iostream>
2#include <cstring>
3
4int main() {
5 char str1[20] = "Hello, ";
6 char str2[] = "World!";
7
8 // Concatenating strings
9 strcat(str1, str2);
10
11 // Printing the concatenated string
12 std::cout << "Concatenated String: " << str1 << std::endl;
13
14 // Getting the length of the string
15 int len = strlen(str1);
16 std::cout << "Length of String: " << len << std::endl;
17
18 return 0;
19}
Output
Concatenated String: Hello, World!
Length of String: 12

Common Pitfalls with C-style Strings

  • Buffer Overflow: Since arrays have fixed sizes, it's easy to exceed their bounds if not careful.
  • Null Character Handling: Every string must end with a null character. Forgetting this can lead to undefined behavior.

Warning

Always ensure that your strings are properly null-terminated and do not exceed the allocated memory size.

The std::string Class

What is std::string?

The std::string class, defined in the &lt;string&gt; header, provides a safer and more convenient way to handle strings. It automatically manages memory and offers numerous methods for string manipulation.

Example: Basic std::string Usage

basic_string.cpp
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string str = "Hello, World!";
6
7 // Printing the string
8 std::cout << "String: " << str << std::endl;
9
10 // Getting the length of the string
11 int len = str.length();
12 std::cout << "Length of String: " << len << std::endl;
13
14 return 0;
15}
Output
String: Hello, World!
Length of String: 12

Common Methods in std::string

  • length(): Returns the length of the string.
  • substr(start, length): Extracts a substring starting from start with the specified length.
  • find(substring): Searches for the first occurrence of substring and returns its position. If not found, returns std::string::npos.
  • replace(start, length, new_string): Replaces a portion of the string with new_string.
  • append(string_to_append): Appends another string to the end.

Example: Using std::string Methods

string_methods.cpp
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string str = "Hello, World!";
6
7 // Finding a substring
8 size_t pos = str.find("World");
9 if (pos != std::string::npos) {
10 std::cout << "Substring found at position: " << pos << std::endl;
11
12 // Replacing the substring
13 str.replace(pos, 5, "Universe");
14 std::cout << "Modified String: " << str << std::endl;
15 }
16
17 // Appending to the string
18 str.append(" Welcome!");
19 std::cout << "Final String: " << str << std::endl;
20
21 return 0;
22}
Output
Substring found at position: 7
Modified String: Hello, Universe!
Final String: Hello, Universe! Welcome!

Comparing Strings

Strings can be compared using relational operators (==, !=, <, >, <=, >=) or the compare() method.

Example: Comparing Strings

string_comparison.cpp
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string str1 = "apple";
6 std::string str2 = "banana";
7
8 if (str1 == str2) {
9 std::cout << "Strings are equal." << std::endl;
10 } else {
11 std::cout << "Strings are not equal." << std::endl;
12 }
13
14 // Using compare method
15 int result = str1.compare(str2);
16 if (result < 0) {
17 std::cout << "str1 is less than str2" << std::endl;
18 } else if (result > 0) {
19 std::cout << "str1 is greater than str2" << std::endl;
20 } else {
21 std::cout << "str1 is equal to str2" << std::endl;
22 }
23
24 return 0;
25}
Output
Strings are not equal.
str1 is less than str2

Reading Strings with Spaces

To read strings that include spaces, use std::getline() instead of the extraction operator (>>).

Example: Using getline to Read a String

getline_example.cpp
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string fullName;
6
7 std::cout << "Enter your full name: ";
8 std::getline(std::cin, fullName);
9
10 std::cout << "Hello, " << fullName << "!" << std::endl;
11
12 return 0;
13}
Output
Enter your full name: John Doe
Hello, John Doe!

Practical Example

Let's create a simple program that reads a user's name and address, manipulates the strings, and then displays them.

Example: Full String Manipulation Program

string_program.cpp
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string firstName, lastName, address;
6
7 // Reading full name
8 std::cout << "Enter your first name: ";
9 std::cin >> firstName;
10 std::cout << "Enter your last name: ";
11 std::cin >> lastName;
12
13 // Concatenating names
14 std::string fullName = firstName + " " + lastName;
15
16 // Reading address
17 std::cout << "Enter your address: ";
18 std::getline(std::cin, address);
19
20 // Displaying information
21 std::cout << "
22Full Name: " << fullName << std::endl;
23 std::cout << "Address: " << address << std::endl;
24
25 return 0;
26}
Output
Enter your first name: John
Enter your last name: Doe
Enter your address: 123 Main St, Anytown

Full Name: John Doe
Address: 123 Main St, Anytown

Summary

  • C-style Strings: Arrays of characters terminated by '\0', manipulated using functions from &lt;cstring&gt;.
  • std::string Class: Part of STL, offers safer and more convenient methods for string manipulation.
  • Common Methods: length(), substr(), find(), replace(), append().
  • String Comparison: Using relational operators or compare() method.
  • Reading Strings: Use std::getline() to read strings with spaces.
MethodDescription
length()Returns the length of the string.
substr()Extracts a substring from the string.
find()Searches for a substring in the string.
replace()Replaces a portion of the string.
append()Appends another string to the end.

What's Next?

In the next tutorial, we will explore Structures (struct), which allow you to group related data together into a single unit. This will be particularly useful for creating more complex data types and organizing your code effectively.

Stay tuned!


PreviousPassing Array to a FunctionNext Structures (struct)

Recommended Gear

Passing Array to a FunctionStructures (struct)