C-Style Strings and std::string of STL
In C++, strings are a sequence of characters used to represent text. C++ provides two primary ways to handle strings:
Key notes
- 1. C-Style Strings: Character arrays (from the C language).
- 2. std::string: A more modern and flexible string class provided by the Standard Template Library (STL).
1. C-Style Strings
A C-style string is a null-terminated character array.
Example
#include <iostream>
#include <cstring> // For string functions like strlen, strcpy
int main() {
char str1[] = "Hello"; // String literal
char str2[20]; // Array for storing strings
std::cout << "Length of str1: " << strlen(str1) << std::endl; // Length of the string
strcpy(str2, str1); // Copy str1 into str2
strcat(str2, ", World!"); // Concatenate strings
std::cout << "str2: " << str2 << std::endl; // Output: Hello, World!
return 0;
}
Common Functions in <cstring>
• strlen(char*): Get the length of a string.
• strcpy(dest, src): Copy one string to another.
• strcat(dest, src): Concatenate strings.
• strcmp(str1, str2): Compare two strings.
Limitations
• Fixed size: Requires pre-defining the array size.
• Manual memory management: Risk of buffer overflows.
2. std::string (Preferred in Modern C++)
The std::string class is part of the C++ Standard Library and provides a safer, easier, and more flexible way to work with strings.
Key Features
• Dynamic sizing.
• Supports many useful operations as member functions.
• Automatically manages memory.
Example
#include <iostream>
#include <string> // Required for std::string
int main() {
std::string str1 = "Hello"; // Initialize with a literal
std::string str2 = "World";
// Concatenate strings using +
std::string combined = str1 + ", " + str2 + "!";
// Length of the string
std::cout << "Length: " << combined.length() << std::endl;
// Access individual characters
std::cout << "First character: " << combined[0] << std::endl;
// Substring
std::cout << "Substring: " << combined.substr(7, 5) << std::endl; // Output: World
// Find a substring
size_t pos = combined.find("World");
if (pos != std::string::npos) {
std::cout << "'World' found at position: " << pos << std::endl;
}
// Replace part of the string
combined.replace(7, 5, "Universe");
std::cout << "Replaced string: " << combined << std::endl;
return 0;
}
Key Functions of std::string
• Length and Capacity:
• .length() or .size(): Returns the number of characters.
• .capacity(): Returns the total allocated capacity.
• Modifying Strings:
• .append(): Appends another string.
• .insert(pos, str): Inserts a string at a position.
• .erase(pos, len): Erases characters from a position.
• .replace(pos, len, str): Replaces part of the string.
• Substring and Search:
• .substr(pos, len): Extracts a substring.
• .find(str): Finds the first occurrence of a substring.
• .rfind(str): Finds the last occurrence of a substring.
• Comparison:
• ==, !=, <, >: Direct comparison operators for strings.
• Access:
• str[index]: Access a character at a specific position.
3. Converting Between C-Style Strings and std::string
From C-Style to std::string:
char cstr[] = "Hello, World!";
std::string str = cstr; // Automatic conversion
From std::string to C-Style:
std::string str = "Hello, World!";
const char* cstr = str.c_str(); // Returns a C-style null-terminated string
Comparison Between C-Style Strings and std::string
Feature | C-Style Strings | std::string |
Memory Management | Manual | Automatic |
Dynamic Size | No | Yes |
Ease of Use | Low | High |
Performance | Faster for small strings | Slight overhead for safety |
Functionality | Limited | Extensive |
Best Practices
1. Prefer std::string over C-style strings for safety and flexibility.
2. Use C-style strings only when required for interoperability with C libraries or performance-critical scenarios.
3. Avoid direct pointer manipulation unless absolutely necessary.