std::unique_copy is an algorithm which can be used to copy elements without duplicating objects in adjacent locations.

template< class InputIt, class OutputIt >
OutputIt uniquecopy( InputIt first, InputIt last, OutputIt dfirst );

Usage example:

C++
#include 
#include 
#include 
#include 

int main()
{
    std::string s1 = "This is   a story   about       hhhhero!";
    std::cout << s1 << std::endl;

    std::string s2;
    std::unique_copy(s1.begin(), s1.end(), std::back_inserter(s2));

    std::cout <<  s2 << std::endl;
    return 0;
}

output:

Bash
This is   a story   about       hhhhero!

This is a story about hero!

Add lambda expressions to remove duplicating space:

C++
    std::unique_copy(s1.begin(), s1.end(), std::back_inserter(s2),
                     [](const char c1, const char c2){ return (c1 == ' ' && c2 == ' '); });

output:

Bash
This is   a story   about       hhhhero!

This is a story about hhhhero!

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Content Summary
: Input your strings, the tool can get a brief summary of the content for you.

X
0
Would love your thoughts, please comment.x
()
x