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 164 views
1 answer 130 views
1 answer 138 views
1 answer 123 views
1 answer 84 views
1 answer 121 views
...