#include <iostream>
#include <string>
#include <algorithm>
// Function to normalize whitespace: collapses consecutive spaces and trims edges
std::string removeExtraWhitespace(std::string str) {
// Step 1: Normalize all whitespace characters (tabs, newlines, etc.) to standard spaces
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char ch) {
return std::isspace(ch) ? ' ' : ch;
});
// Step 2: Collapse consecutive spaces into a single space in-place using std::unique
// std::unique moves duplicate adjacent elements to the end and returns an iterator
// to the new boundary
auto new_end = std::unique(str.begin(), str.end(), [](char lhs, char rhs) {
return lhs == ' ' && rhs == ' ';
});
// Erase the leftover duplicate elements beyond the new boundary
str.erase(new_end, str.end());
// Step 3: Trim leading space if present
if (!str.empty() && str.front() == ' ') {
str.erase(str.begin());
}
// Step 4: Trim trailing space if present
if (!str.empty() && str.back() == ' ') {
str.pop_back();
}
return str;
}
int main() {
std::string s = " This is a test string with extra spaces. ";
// Clean the string
std::string cleaned = removeExtraWhitespace(s);
std::cout << cleaned << std::endl;
}
/*
run:
This is a test string with extra spaces.
*/