Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Comprehensive Guide to C++ String Manipulation

Tech May 19 1

Understanding C++ Strings

Strings are fundamental data structures in computer science, representing a sequence of characters. In C++, they're typically implemented as character arrays with a null terminator (\0) marking the end. The standard library provides robust string handling through the std::string class.

Common String Applications

  • Text Processing:
    • Searching for substrings within larger text
    • Replacing specific text patterns
  • File Path Operations:
    • Extracting directory names and filenames
    • Constructing URLs and query strings
  • Personal Data Handling:
    • Concatenating or splitting names
  • Validation:
    • Password complexity checks
    • Regular expression matching for email/phone validation
  • Data Parsing:
    • JSON/XML document processing

String Declaration

To use strings in C++, include the string header:

#include <string>

Then declare a string variable:

int main() {
    std::string textData;
}

Assigning Values to Strings

1. Input Assignment

Using getline() for complete line input:

std::getline(std::cin, textData); // Preserves spaces

Using cin for word-based input:

std::cin >> textData; // Stops at whitespace

2. Direct Assignment

Assigning literal values:

textData = "Hello, World!";

String Output

Strings can be output using standard stream operaotrs:

std::cout << "Input received: " << textData << std::endl;

String Insertion

The insert() method allows inserting text at specific positions:

#include <iostream>
#include <string>

int main() {
    std::string base = "Good morning";
    std::string addition = "very ";

    base.insert(5, addition);

    std::cout << base << std::endl;
    return 0;
}

Alternative insertion methods:

// Append to end
base += ", how are you?";

// Add single character
base.push_back('?');

String Length Calculation

Use the .size() or .length() method:

std::string sample = "example";
int length = sample.size();

Important Considerations

  • getline() reads entire lines including spaces
  • When mixing cin and getline(), clear input buffer: ``` std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n');
  • Always validate user input to prevent errors
  • std::string handles memory automatically, unlike C-style strings

String Traversal

1. Index-Based Access

#include <iostream>
#include <string>

int main() {
    std::string message = "Hello, World!";
    for (size_t i = 0; i < message.length(); ++i) {
        std::cout << message[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

2. Iterator-Based Traversal

#include <iostream>
#include <string>

int main() {
    std::string message = "Hello, World!";
    for (auto it = message.begin(); it != message.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    return 0;
}

Practice Problem: Shortest Substring Containing Subsequence

Given a string s, find the shortest substring that contains "wotojo" as a subsequence.

Input: A string s
Output: Length of the shortest valid substring

Example:
Input: wwowoxtoyjotojo
Output: 8 (substring: woxtoyjo)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main() {
    std::string input;
    std::cin >> input;
    
    std::vector<int> results;
    int n = input.length();
    
    for (int i = 0; i < n; ++i) {
        if (input[i] == 'w') {
            int state = 1;
            int endPos = i;
            int count = 1;
            
            for (int j = i + 1; j < n; ++j) {
                if (state == 1 && input[j] == 'o') {
                    state = 2;
                } else if (state == 2 && input[j] == 't') {
                    state = 3;
                } else if (state == 3 && input[j] == 'o') {
                    state = 4;
                } else if (state == 4 && input[j] == 'j') {
                    state = 5;
                } else if (state == 5 && input[j] == 'o') {
                    state = 6;
                    endPos = j;
                    break;
                }
                count++;
            }
            
            if (state == 6) {
                results.push_back(endPos - i + 1);
            }
        }
    }
    
    if (!results.empty()) {
        std::sort(results.begin(), results.end());
        std::cout << results[0] << std::endl;
    }
    
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.