HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Removing whitespaces in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whitespacesstringremoving

Problem

I wrote this function to remove whitespaces in strings. Please help me improve it. I intended to use the function for a Big Integer ADT.

#include 
#include 
#include 

void rs(char* str){
    int i(0);
    int j(0);

    while((*(str + i) = *(str + j++)) != '\0')
        if(*(str + i) != ' ')
            i++;
    return;
}

int main()
{
    std::string str = "Hello World";
    char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
    rs(result);

    std::cout << result << std::endl;

    return 0;
}

Solution

char* result = strcpy((char*)malloc(str.length()+1), str.c_str());


This seems more suited for a C program than a C++ one. In fact, with C++11, you don't need to write your own function.

Behold: std::remove_if

Note:


std::remove_if


Removes all elements satisfying specific criteria from the range
[first, last) and returns a past-the-end iterator for the new end of
the range.


A call to remove is typically followed by a call to a container's
erase method, which erases the unspecified values and reduces the
physical size of the container to match its new logical size.

This is what you would do:

str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());


I am not sure if this is the safest or most efficient method, but I think it's definitely an improvement to what you have done.

Code Snippets

char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());

Context

StackExchange Code Review Q#64958, answer score: 6

Revisions (0)

No revisions yet.