#include <iostream>
#include <string>
#include <regex>
std::string replaceMultipleSpaces(const std::string& str) {
// Use regex to match and replace multiple spaces with a single space
std::regex spaceRegex("\\s+");
std::string output = std::regex_replace(str, spaceRegex, " ");
// Trim leading and trailing spaces (optional)
size_t start = output.find_first_not_of(' ');
size_t end = output.find_last_not_of(' ');
if (start == std::string::npos) {
return ""; // Return an empty string if there are only spaces
}
return output.substr(start, end - start + 1);
}
int main() {
std::string str = " This is a string with multiple spaces ";
std::string output = replaceMultipleSpaces(str);
std::cout << "\"" << output << "\"" << std::endl;
return 0;
}
/*
run:
"This is a string with multiple spaces"
*/