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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,693 questions

57,001 answers

573 users

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

2 Answers

0 votes
#include <iostream>
#include <algorithm> 

std::string &ltrim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    s.erase(0, s.find_first_not_of(chars));
    return s;
}
  
std::string &rtrim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    s.erase(s.find_last_not_of(chars) + 1);
    return s;
}
  
std::string &trim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    return ltrim(rtrim(s, chars), chars);
}

std::string remove_extra_spaces(const std::string &s) {
    std::string output = "";

    unique_copy(s.begin(), s.end(), std::back_insert_iterator<std::string>(output),
                                     [](char a,char b){ return isspace(a) && isspace(b);});  
    return output;
}
 
int main()
{
    std::string s = "    c++ python      c     java php   ";

    s = remove_extra_spaces(s);
    
    s = trim(s);
    
    std::cout << s;
  
    return 0;
}
 
 
 
 
/*
run:
 
c++ python c java php
 
*/

 



answered Feb 26, 2021 by avibootz
0 votes
#include <iostream>
#include <regex>

std::string &ltrim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    s.erase(0, s.find_first_not_of(chars));
    return s;
}
   
std::string &rtrim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    s.erase(s.find_last_not_of(chars) + 1);
    return s;
}
   
std::string &trim(std::string &s, const std::string &chars = "\t\n\v\f\r ") {
    return ltrim(rtrim(s, chars), chars);
}

int main() {
    std::string s = "    c++ python      c     java php   ";
    
    std::regex re("\\s+");
    s = std::regex_replace(s, re, " ");
 
    s = trim(s);
     
    std::cout << s;

    return 0;
}




/*
run:

c++ python c java php

*/

 



answered Feb 26, 2021 by avibootz

Related questions

1 answer 286 views
1 answer 230 views
1 answer 278 views
1 answer 254 views
1 answer 216 views
...