Mastering String Operations in C++: A Practical Guide

Hello everyone! Today I want to share with you a super useful skill in C++: string operations. Whether it’s processing CSV files or extracting web links, once you master the basic operations of strings, these tasks can be easily accomplished! It’s like magic; let’s play with strings together!

1. Basic String Operations

In C++, we mainly use std::string to handle strings. It’s like a pocket full of characters, where we can add, delete, or modify content.

#include <string>
#include <iostream>

int main() {
    std::string text = "Hello, C++!";
    
    // Get string length
    std::cout << "Length: " << text.length() << std::endl;
    
    // Access a single character
    std::cout << "First character: " << text[0] << std::endl;
    
    // String concatenation
    std::string name = "Xiao Ming";
    std::string greeting = "Hello, " + name;
    
    // Substring extraction
    std::string sub = text.substr(0, 5);  // Extract 5 characters starting from index 0
}

2. String Searching

Imagine a string as a book, and we want to find a specific “keyword” in it. C++ provides various searching methods:

std::string text = "C++ is amazing, C++ is powerful!";

// Find the position of the first occurrence
size_t pos = text.find("C++");
if (pos != std::string::npos) {
    std::cout << "Found! Position: " << pos << std::endl;
}

// Start searching from a specified position
pos = text.find("C++", pos + 1);  // Find the second "C++"

// Find the position of the last occurrence
pos = text.rfind("C++");

// Find any character
pos = text.find_first_of("aeiou");  // Find the first vowel

Tip: std::string::npos is a special value indicating “not found,” like a predetermined code!

3. String Replacement and Modification

Sometimes we need to perform a “makeover” on strings, replacing or modifying their contents:

std::string text = "Hello, world!";

// Replace substring
text.replace(0, 5, "Hi");  // Replace the first 5 characters with "Hi"

// Insert string
text.insert(3, "lovely ");  // Insert string at position 3

// Delete characters
text.erase(0, 3);  // Delete the first 3 characters

// Clear string
text.clear();

// Resize string
text.resize(10, '*');  // Resize to 10 characters, filling with * if not enough

4. Practical Example: CSV File Parsing

Let’s write a simple CSV parser to split a string into data items:

#include <vector>
#include <sstream>

std::vector<std::string> splitCSV(const std::string& line) {
    std::vector<std::string> result;
    std::stringstream ss(line);
    std::string item;
    
    // Use getline to split by comma
    while (std::getline(ss, item, ',')) {
        // Trim whitespace
        size_t first = item.find_first_not_of(" \t");
        size_t last = item.find_last_not_of(" \t");
        if (first != std::string::npos && last != std::string::npos) {
            item = item.substr(first, last - first + 1);
        }
        result.push_back(item);
    }
    
    return result;
}

5. Practical Example: Extracting Web Links

This example demonstrates how to extract links from HTML text:

std::vector<std::string> extractLinks(const std::string& html) {
    std::vector<std::string> links;
    std::string href = "href=\"";
    size_t pos = 0;
    
    while ((pos = html.find(href, pos)) != std::string::npos) {
        // Find the position of href="
        size_t start = pos + href.length();
        // Find the next quote position
        size_t end = html.find("\"", start);
        
        if (end != std::string::npos) {
            // Extract link
            std::string link = html.substr(start, end - start);
            if (!link.empty()) {
                links.push_back(link);
            }
        }
        pos = end + 1;
    }
    
    return links;
}

Important Notes:

  • Be mindful of boundary conditions when performing string operations.
  • When concatenating many strings, it’s best to use std::stringstream.
  • Special care is needed when handling multi-byte character sets like UTF-8.
  • String searching is case-sensitive.

Practice Questions:

  1. How to count the occurrences of a word in a string?
  2. Write a function to convert all lowercase letters in a string to uppercase.
  3. How to verify if a string is a palindrome?

Friends, today’s journey of learning C++ ends here! Remember to code actively, and feel free to ask me any questions in the comments. Wishing everyone a happy learning experience and continuous improvement in C++!

Leave a Comment