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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to remove extra whitespace from a string in C++

2 Answers

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

// ------------------------------------------------------------
// normalizeWhitespace
// ------------------------------------------------------------
// Removes extra whitespace from a string:
//
// - Trim leading whitespace
// - Trim trailing whitespace
// - Collapse multiple internal whitespace into a single space
//
// The algorithm performs a single linear scan and builds a
// cleaned result string.
// ------------------------------------------------------------
std::string normalizeWhitespace(const std::string& input) {

    std::string out;
    out.reserve(input.size());   // Reserve capacity for efficiency

    bool inWhitespace = false;   // Tracks whether we're inside a whitespace run
    bool started = false;        // Tracks whether we've copied the first non-space

    for (char ch : input) {

        if (std::isspace(static_cast<unsigned char>(ch))) {

            // Skip leading whitespace
            if (!started) {
                continue;
            }

            // Skip repeated whitespace inside the string
            if (inWhitespace) {
                continue;
            }

            // First whitespace after a word → write a single space
            out.push_back(' ');
            inWhitespace = true;

        } else {
            // Non-whitespace character
            out.push_back(ch);
            inWhitespace = false;
            started = true;
        }
    }

    // Remove trailing space if present
    if (!out.empty() && out.back() == ' ') {
        out.pop_back();
    }

    return out;
}

int main() {

    std::string s = "   This   is   a   test   string   with         extra   spaces.   ";

    std::string cleaned = normalizeWhitespace(s);

    std::cout << "Original: [" << s << "]\n";
    std::cout << "Cleaned:  [" << cleaned << "]\n";
}


/*
run:

Original: [   This   is   a   test   string   with         extra   spaces.   ]
Cleaned:  [This is a test string with extra spaces.]

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
0 votes
#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.

*/

 



answered 2 days ago by avibootz
edited 1 day ago by avibootz
...