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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to replace multiple spaces in a string with a single space between words in C++

2 Answers

0 votes
#include <iostream>
#include <sstream>
#include <string>

std::string removeExtraSpaces(const std::string& str) {
    std::stringstream ss(str);
    std::string word, result;

    // Extract words separated by spaces
    while (ss >> word) {
        if (!result.empty()) {
            result += " "; // Add a single space before appending the next word
        }
        result += word;
    }

    return result;
}

int main() {
    std::string str = "    This   is    a    string with  multiple    spaces  ";
    
    std::string output = removeExtraSpaces(str);

    std::cout << "\"" << output << "\"" << "\n";

    return 0;
}


/*
run:

"This is a string with multiple spaces"

*/

 



answered Apr 4, 2025 by avibootz
edited Apr 4, 2025 by avibootz
0 votes
#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"

*/

 



answered Apr 4, 2025 by avibootz
...