#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!'
*/