Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to get the middle part of a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

/*
    Middle‑substring extractor in C++
    ---------------------------------
    This program demonstrates how to extract the "middle" part of a string.
    Definition of "middle":
        - A substring centered around the midpoint of the string.
        - Caller specifies how many characters to extract.

    Architecture notes:
        - A dedicated function handles extraction.
        - Main runs a predefined test suite.
        - Uses std::string::substr and std::string::size for clarity.
        - No dynamic allocation; memory usage is predictable.

    Performance notes:
        - substr() is O(n) due to allocation of the new string.
        - size() is O(1).
        - For typical string sizes, performance is excellent.

    Pitfalls:
        - Negative lengths or zero-length requests must be handled.
        - If requested length exceeds string size, return the whole string.
        - For UTF‑8, std::string operates on bytes, not characters.

    Edge cases tested:
        - Empty string
        - Very short strings
        - Odd/even lengths
        - Length requests larger than the string
        - Mixed characters (#, !, etc.)
*/

/**
 * Extracts the middle part of a string.
 *
 * @param s       Input string.
 * @param length  Number of characters to extract.
 *
 * @return        Middle substring.
 *
 * Error handling:
 *   - If length <= 0 → return empty string.
 *   - If string is empty → return empty string.
 *   - If length >= s.size() → return original string.
 *
 * Complexity:
 *   - O(n) due to substring allocation.
 */
std::string getMiddleSubstring(const std::string& s, std::size_t length) {
    const std::size_t total = s.size();

    if (length == 0 || total == 0) {
        return "";
    }

    if (length >= total) {
        return s;
    }

    // Midpoint index
    const std::size_t mid = total / 2;

    // Compute start index so substring is centered
    std::size_t start = mid - (length / 2);

    // Bounds correction
    if (start > total) {
        start = 0;
    }
    if (start + length > total) {
        length = total - start;
    }

    return s.substr(start, length);
}

int main() {
    std::cout << "Middle‑substring extraction tests:\n\n";

    // Test suite (converted from PHP array)
    struct TestCase {
        std::string input;
        std::size_t length;
    };

    std::vector<TestCase> tests = {
        {"",                 3},
        {"A",                1},
        {"AB",               1},
        {"HelloWorld",       4},
        {"MiddleTest",       5},
        {"Short",            10},
        {"ABCDE",            2},
        {"ABCDE",            3},
        {"abcde#www!opqrst", 3},
    };

    for (const auto& t : tests) {
        std::string result = getMiddleSubstring(t.input, t.length);

        std::cout << "Input: '" << t.input
                  << "' | Length: " << t.length
                  << " → Middle: '" << result << "'\n";
    }
}


/*
run:

Middle‑substring extraction tests:

Input: '' | Length: 3 → Middle: ''
Input: 'A' | Length: 1 → Middle: 'A'
Input: 'AB' | Length: 1 → Middle: 'B'
Input: 'HelloWorld' | Length: 4 → Middle: 'loWo'
Input: 'MiddleTest' | Length: 5 → Middle: 'dleTe'
Input: 'Short' | Length: 10 → Middle: 'Short'
Input: 'ABCDE' | Length: 2 → Middle: 'BC'
Input: 'ABCDE' | Length: 3 → Middle: 'BCD'
Input: 'abcde#www!opqrst' | Length: 3 → Middle: 'ww!'

*/

 



answered 1 day ago by avibootz

Related questions

1 answer 249 views
1 answer 133 views
2 answers 287 views
2 answers 336 views
1 answer 229 views
...