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.
C++ provides two main ways to handle strings:
'\0'). They are similar to strings in other C-like languages.Understanding both approaches will help you choose the right tool for different scenarios, ensuring efficient and error-free code.
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:
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'.
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.1#include <iostream>2#include <cstring>34int main() {5char str1[20] = "Hello, ";6char str2[] = "World!";78// Concatenating strings9strcat(str1, str2);1011// Printing the concatenated string12std::cout << "Concatenated String: " << str1 << std::endl;1314// Getting the length of the string15int len = strlen(str1);16std::cout << "Length of String: " << len << std::endl;1718return 0;19}
Concatenated String: Hello, World! Length of String: 12
Warning
The std::string class, defined in the <string> header, provides a safer and more convenient way to handle strings. It automatically manages memory and offers numerous methods for string manipulation.
1#include <iostream>2#include <string>34int main() {5std::string str = "Hello, World!";67// Printing the string8std::cout << "String: " << str << std::endl;910// Getting the length of the string11int len = str.length();12std::cout << "Length of String: " << len << std::endl;1314return 0;15}
String: Hello, World! Length of String: 12
start with the specified length.substring and returns its position. If not found, returns std::string::npos.new_string.1#include <iostream>2#include <string>34int main() {5std::string str = "Hello, World!";67// Finding a substring8size_t pos = str.find("World");9if (pos != std::string::npos) {10std::cout << "Substring found at position: " << pos << std::endl;1112// Replacing the substring13str.replace(pos, 5, "Universe");14std::cout << "Modified String: " << str << std::endl;15}1617// Appending to the string18str.append(" Welcome!");19std::cout << "Final String: " << str << std::endl;2021return 0;22}
Substring found at position: 7 Modified String: Hello, Universe! Final String: Hello, Universe! Welcome!
Strings can be compared using relational operators (==, !=, <, >, <=, >=) or the compare() method.
1#include <iostream>2#include <string>34int main() {5std::string str1 = "apple";6std::string str2 = "banana";78if (str1 == str2) {9std::cout << "Strings are equal." << std::endl;10} else {11std::cout << "Strings are not equal." << std::endl;12}1314// Using compare method15int result = str1.compare(str2);16if (result < 0) {17std::cout << "str1 is less than str2" << std::endl;18} else if (result > 0) {19std::cout << "str1 is greater than str2" << std::endl;20} else {21std::cout << "str1 is equal to str2" << std::endl;22}2324return 0;25}
Strings are not equal. str1 is less than str2
To read strings that include spaces, use std::getline() instead of the extraction operator (>>).
1#include <iostream>2#include <string>34int main() {5std::string fullName;67std::cout << "Enter your full name: ";8std::getline(std::cin, fullName);910std::cout << "Hello, " << fullName << "!" << std::endl;1112return 0;13}
Enter your full name: John Doe Hello, John Doe!
Let's create a simple program that reads a user's name and address, manipulates the strings, and then displays them.
1#include <iostream>2#include <string>34int main() {5std::string firstName, lastName, address;67// Reading full name8std::cout << "Enter your first name: ";9std::cin >> firstName;10std::cout << "Enter your last name: ";11std::cin >> lastName;1213// Concatenating names14std::string fullName = firstName + " " + lastName;1516// Reading address17std::cout << "Enter your address: ";18std::getline(std::cin, address);1920// Displaying information21std::cout << "22Full Name: " << fullName << std::endl;23std::cout << "Address: " << address << std::endl;2425return 0;26}
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
'\0', manipulated using functions from <cstring>.length(), substr(), find(), replace(), append().compare() method.std::getline() to read strings with spaces.| Method | Description |
|---|---|
| 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. |
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!