String Handling in C++: C-Style and std::string
Learn string handling in C++ using C-style strings and std::string for text processing, concatenation, and manipulation.
In C++, text (string) operations can be performed using both traditional C-style character arrays (char arrays)
and the modern std::string class.
C-style arrays provide low-level control, while the std::string class is safer and more convenient.
In this article, we’ll explore all aspects of working with strings in detail.
1. C-Style Strings (char arrays)
C-style strings are char arrays terminated by a null character ('\0').
They are stored in memory as a contiguous sequence of characters.
#include <iostream>
using namespace std;
int main() {
char message1[] = "Hello"; // '\0' is added automatically
char message2[20] = "C++"; // Maximum 19 characters + '\0'
cout << message1 << " " << message2 << endl;
return 0;
}
When working with C-style strings, it is crucial to avoid exceeding the array’s boundary. C++ does not automatically check array limits for C-style strings.
2. strcpy, strcat, strlen, strcmp (C String Functions)
When using C-style strings, the functions from the <cstring> library are commonly used:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[20] = "C++";
char b[20] = "Programming";
// Concatenation
strcat(a, " "); // a = "C++ "
strcat(a, b); // a = "C++ Programming"
// Copy
char c[20];
strcpy(c, a);
// Length
cout << "Length: " << strlen(a) << endl;
// Comparison
if (strcmp(a, c) == 0)
cout << "A and C are equal." << endl;
cout << "Result: " << a << endl;
}
These functions must be used carefully, as they can cause buffer overflows.
In modern C++, it is recommended to use std::string instead.
3. Introduction to the std::string Class
In modern C++, the <string> library is used for text manipulation.
std::string objects can grow dynamically, handle memory management automatically, and provide rich functionality.
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "Ali";
string lastName = "Yilmaz";
string fullName = firstName + " " + lastName;
cout << "Hello " << fullName << endl;
return 0;
}
The std::string type can easily be concatenated using the + operator
and compared directly using ==.
4. Basic String Operations
| Operation | Description | Example |
|---|---|---|
| Concatenation | Joins two strings | a + b |
| Length | Returns the number of characters | a.length() or a.size() |
| Character access | Access by index | a[0], a.at(2) |
| Substring | Extracts a portion of a string | a.substr(2, 4) |
| Comparison | Alphabetical comparison | a.compare(b) |
| Empty? | Checks if string is empty | a.empty() |
| Clear | Deletes the content | a.clear() |
string text = "Programming";
cout << text.length() << endl; // 11
cout << text.substr(0, 7) << endl; // "Program"
5. Searching, Replacing, and Erasing
std::string provides many powerful text manipulation methods:
string message = "C++ programming language";
// Search
size_t position = message.find("programming");
if (position != string::npos)
cout << "'programming' found at index: " << position << endl;
// Replace
message.replace(4, 11, "modern"); // replace 11 characters starting from index 4
cout << message << endl; // "C++ modern language"
// Erase
message.erase(4, 7); // delete 7 characters starting from index 4
cout << message << endl; // "C++ language"
The find() method returns string::npos if the substring is not found.
This value indicates “not found”.
6. Character-Level Operations
Since a string consists of characters, it can be processed character by character using loops.
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "Cplusplus";
for (char c : word) {
cout << c << " ";
}
cout << endl;
// Convert to uppercase
for (char &c : word) {
c = toupper(c);
}
cout << word << endl;
}
For character conversions, use <cctype> functions such as
toupper() and tolower().
7. Conversion Operations (string <→ int, double)
A std::string can be converted to numeric values and vice versa.
#include <iostream>
#include <string>
using namespace std;
int main() {
string numberText = "42";
int number = stoi(numberText); // string → int
double d = stod("3.14"); // string → double
cout << number + 10 << endl; // 52
cout << d * 2 << endl; // 6.28
// int → string
int age = 25;
string text = to_string(age);
cout << "Age: " << text << endl;
}
8. Comparison (compare, ==, <, >)
Strings can be compared using either the compare() method or comparison operators.
string a = "Ali";
string b = "Veli";
if (a == b)
cout << "Equal" << endl;
else if (a < b)
cout << "A comes before alphabetically" << endl;
else
cout << "A comes after alphabetically" << endl;
9. Input and Output Operations
The cin object only reads input until the first whitespace character.
If you want to read an entire sentence, use the getline() function.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << endl;
cin.ignore(); // clear the newline character left in the buffer
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
cout << "You entered: " << sentence << endl;
}
The getline() function reads the entire line, including spaces.
10. Example Application: Text Analysis
The following example counts the number of words and letters in a user-provided sentence.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string text;
cout << "Enter a sentence: ";
getline(cin, text);
int charCount = 0;
int wordCount = 1;
for (char c : text) {
if (isalpha(c))
charCount++;
if (c == ' ')
wordCount++;
}
cout << "Character count: " << charCount << endl;
cout << "Word count: " << wordCount << endl;
return 0;
}
11. TL;DR
- C-style strings are
char[]arrays and must be handled carefully. - Modern C++ recommends using the
std::stringclass. - Basic operations:
+,length(),substr(),find(),replace(),erase(). - Use
stoi(),stod(), andto_string()for numeric conversions. getline()can read text containing spaces.- All examples can be executed in Visual Studio 2022 or GCC 11+ environments.