Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
613 lines (478 loc) · 13.4 KB

File metadata and controls

613 lines (478 loc) · 13.4 KB

🚀 C++ Strings: Complete Guide

📚 Overview

Strings are fundamental for text processing in C++. C++ provides both C-style character arrays and the modern std::string class. Understanding both approaches and their trade-offs is essential for effective programming.

🎯 Key Concepts

String Types in C++

  • C-style strings: Null-terminated character arrays
  • std::string: Modern C++ string class with automatic memory management
  • String literals: Compile-time string constants

🔧 C-Style Strings

Basic Declaration

#include<iostream>
#include<cstring>usingnamespacestd;intmain() {
// Character array (C-style string)char str1[] = "Hello";
char str2[10] = "World";
char str3[20]; // Uninitialized// String literalconstchar* str4 = "Hello World";
// Character by character initializationchar str5[] = {'H', 'e', 'l', 'l', 'o', '\0'};
return0;
}

String Operations

intmain() {
char str1[20] = "Hello";
char str2[20] = "World";
// String length
cout << "Length: " << strlen(str1) << endl; // 5// String copystrcpy(str1, str2); // str1 becomes "World"// String concatenationstrcat(str1, "!");
cout << "Result: " << str1 << endl; // "World!"// String comparisonif (strcmp(str1, "World!") == 0) {
cout << "Strings are equal" << endl;
}
return0;
}

Common C String Functions

intmain() {
char str[100] = "Hello World";
// Lengthsize_t len = strlen(str);
// Copychar dest[100];
strcpy(dest, str);
// Copy with length limitstrncpy(dest, str, 5); // Copy only 5 characters
dest[5] = '\0'; // Ensure null termination// Concatenatestrcat(dest, "!!!");
// Compareint result = strcmp(str, dest);
if (result < 0) cout << "str < dest" << endl;
elseif (result > 0) cout << "str > dest" << endl;
else cout << "str == dest" << endl;
// Find characterchar* found = strchr(str, 'o'); // Find first 'o'if (found) {
cout << "Found 'o' at: " << (found - str) << endl;
}
// Find substringchar* substr = strstr(str, "World");
if (substr) {
cout << "Found 'World' at: " << (substr - str) << endl;
}
return0;
}

🚀 Modern C++ Strings (std::string)

Basic String Operations

#include<string>
#include<iostream>usingnamespacestd;intmain() {
// String declaration
string str1 = "Hello";
string str2("World");
string str3(5, 'x'); // 5 copies of 'x'// String assignment
str1 = "New Hello";
str1.assign("Another Hello");
// String concatenation
string result = str1 + "" + str2;
str1 += "" + str2;
// String comparisonif (str1 == str2) {
cout << "Strings are equal" << endl;
}
if (str1 < str2) {
cout << "str1 comes before str2" << endl;
}
return0;
}

String Access and Iteration

intmain() {
string str = "Hello World";
// Access individual characterschar first = str[0]; // 'H'char last = str.at(str.length() - 1); // 'd'// String properties
cout << "Length: " << str.length() << endl;
cout << "Size: " << str.size() << endl;
cout << "Empty: " << str.empty() << endl;
cout << "Capacity: " << str.capacity() << endl;
// Iterating through stringfor (size_t i = 0; i < str.length(); i++) {
cout << str[i] << "";
}
cout << endl;
// Range-based for loopfor (char c : str) {
cout << c << "";
}
cout << endl;
// Iterator-based loopfor (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << "";
}
cout << endl;
return0;
}

String Modifications

intmain() {
string str = "Hello World";
// Insert
str.insert(5, " Beautiful "); // "Hello Beautiful World"// Replace
str.replace(6, 9, "Amazing"); // "Hello Amazing World"// Erase
str.erase(6, 7); // "Hello World"// Append
str.append("!!!");
str.push_back('!'); // Add single character// Resize
str.resize(15, '*'); // Resize to 15, fill with '*'// Clear
str.clear();
return0;
}

String Searching

intmain() {
string str = "Hello World Hello";
// Find first occurrencesize_t pos1 = str.find("Hello");
if (pos1 != string::npos) {
cout << "First 'Hello' at: " << pos1 << endl;
}
// Find last occurrencesize_t pos2 = str.rfind("Hello");
if (pos2 != string::npos) {
cout << "Last 'Hello' at: " << pos2 << endl;
}
// Find first occurrence of any charactersize_t pos3 = str.find_first_of("aeiou");
if (pos3 != string::npos) {
cout << "First vowel at: " << pos3 << endl;
}
// Find first occurrence not of any charactersize_t pos4 = str.find_first_not_of("aeiou");
if (pos4 != string::npos) {
cout << "First non-vowel at: " << pos4 << endl;
}
// Substring
string sub = str.substr(6, 5); // "World"return0;
}

🔄 String Conversion

String to Number

#include<string>
#include<iostream>usingnamespacestd;intmain() {
string str1 = "42";
string str2 = "3.14";
// String to integerint num1 = stoi(str1);
long num2 = stol(str1);
// String to floating pointfloat num3 = stof(str2);
double num4 = stod(str2);
// With base specificationint hex = stoi("1A", nullptr, 16); // 26// Error handlingtry {
int invalid = stoi("not a number");
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
}
return0;
}

Number to String

intmain() {
int num1 = 42;
double num2 = 3.14;
// Number to string
string str1 = to_string(num1);
string str2 = to_string(num2);
// With formatting (C++20)// string str3 = format("Number: {}", num1);
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return0;
}

🎭 String Formatting

Basic Formatting

intmain() {
string name = "Alice";
int age = 25;
double height = 1.75;
// String concatenation
string info = "Name: " + name + ", Age: " + to_string(age);
// Using stringstream for complex formatting
#include<sstream>
stringstream ss;
ss << "Name: " << name << ", Age: " << age << ", Height: " << height;
string formatted = ss.str();
// C++20 format (if available)// string formatted = format("Name: {}, Age: {}, Height: {:.2f}", name, age, height);
cout << formatted << endl;
return0;
}

🔧 String Utilities

String Manipulation

#include<algorithm>
#include<cctype>intmain() {
string str = " Hello World ";
// Trim whitespace
str.erase(0, str.find_first_not_of("\t\n\r"));
str.erase(str.find_last_not_of("\t\n\r") + 1);
// Convert to uppercasetransform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercasetransform(str.begin(), str.end(), str.begin(), ::tolower);
// Reverse stringreverse(str.begin(), str.end());
// Sort characterssort(str.begin(), str.end());
// Remove duplicates (requires sorted string)
str.erase(unique(str.begin(), str.end()), str.end());
return0;
}

String Splitting

vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
intmain() {
string text = "apple,banana,cherry,date";
vector<string> fruits = split(text, ',');
for (const string& fruit : fruits) {
cout << fruit << endl;
}
return0;
}

🎯 Performance Considerations

String vs C-String Performance

#include<chrono>voidbenchmark() {
constint iterations = 100000;
// C-string concatenationauto start = chrono::high_resolution_clock::now();
char result[1000] = "";
for (int i = 0; i < iterations; i++) {
strcat(result, "test");
}
auto end = chrono::high_resolution_clock::now();
auto c_time = chrono::duration_cast<chrono::microseconds>(end - start);
// std::string concatenation
start = chrono::high_resolution_clock::now();
string str_result;
for (int i = 0; i < iterations; i++) {
str_result += "test";
}
end = chrono::high_resolution_clock::now();
auto str_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "C-string time: " << c_time.count() << " μs" << endl;
cout << "std::string time: " << str_time.count() << " μs" << endl;
}

Memory Management

intmain() {
string str;
// Reserve capacity to avoid reallocation
str.reserve(1000);
// Add characters (no reallocation until capacity exceeded)for (int i = 0; i < 1000; i++) {
str += 'a';
}
// Shrink to fit
str.shrink_to_fit();
return0;
}

📝 Best Practices

1. Choose the Right String Type

// Use C-strings when:// - Working with C libraries// - Maximum performance is critical// - Memory is very limited// Use std::string when:// - Writing modern C++ code// - Need automatic memory management// - Want rich string operations

2. Efficient String Operations

// Good: Reserve capacity
string result;
result.reserve(1000);
for (int i = 0; i < 1000; i++) {
result += "item";
}
// Bad: Frequent reallocation
string result;
for (int i = 0; i < 1000; i++) {
result += "item"; // May cause multiple reallocations
}

3. Safe String Access

// Good: Check boundsif (index < str.length()) {
char c = str[index];
}
// Good: Use .at() for bounds checkingtry {
char c = str.at(index);
} catch (const out_of_range& e) {
cout << "Index out of range" << endl;
}

4. String Comparison

// Good: Use == for std::stringif (str1 == str2) { /* ... */ }
// Good: Use strcmp for C-stringsif (strcmp(cstr1, cstr2) == 0) { /* ... */ }
// Bad: Don't compare C-strings with ==if (cstr1 == cstr2) { /* This compares pointers! */ }

🚀 Advanced Techniques

Regular Expressions (C++11+)

#include<regex>intmain() {
string text = "Email: john@example.com, Phone: 123-456-7890";
// Email pattern
regex email_pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
// Find all emails
sregex_iterator it(text.begin(), text.end(), email_pattern);
sregex_iterator end;
for (; it != end; ++it) {
cout << "Found email: " << it->str() << endl;
}
// Replace pattern
string result = regex_replace(text, email_pattern, "[EMAIL]");
cout << "Result: " << result << endl;
return0;
}

String Views (C++17+)

#include<string_view>voidprocessString(string_view str) {
// No copying, just view into existing string
cout << "Processing: " << str << endl;
// Can use most string operationsif (str.starts_with("Hello")) {
cout << "Starts with Hello" << endl;
}
}
intmain() {
string str = "Hello World";
processString(str);
processString("Another string"); // Works with string literalsreturn0;
}

🎯 Practice Problems

Problem 1: Check Palindrome

boolisPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) returnfalse;
left++;
right--;
}
returntrue;
}

Problem 2: Find Longest Common Prefix

string longestCommonPrefix(const vector<string>& strs) {
if (strs.empty()) return"";
string prefix = strs[0];
for (const string& str : strs) {
while (str.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return"";
}
}
return prefix;
}

Problem 3: Valid Parentheses

boolisValidParentheses(const string& s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) returnfalse;
if ((c == ')' && st.top() != '(') ||
(c == '}' && st.top() != '{') ||
(c == ']' && st.top() != '[')) {
returnfalse;
}
st.pop();
}
}
return st.empty();
}

📚 Summary

Key takeaways:

  • C-strings: Fast, memory-efficient, but manual management
  • std::string: Safe, feature-rich, automatic memory management
  • Choose wisely based on performance vs. safety requirements
  • Use modern C++ features when available
  • Handle errors properly with bounds checking
  • Optimize performance with reserve() and efficient operations

Master both approaches to write efficient, safe C++ code!


🔗 Related Topics