3
\$\begingroup\$

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 <iostream>
#include <string>
#include <string.h>

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;
}
\$\endgroup\$
1
  • \$\begingroup\$ Why are you using C-String. C++ has its own string class conveniently called std::string \$\endgroup\$ Commented Oct 7, 2014 at 7:23

1 Answer 1

6
\$\begingroup\$
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.

\$\endgroup\$
3
  • \$\begingroup\$ What are the scope operators for in ::isspace \$\endgroup\$
    – user54356
    Commented Oct 7, 2014 at 7:04
  • \$\begingroup\$ You are using isspace from the global namespace. Which in this case is from <ctype.h> \$\endgroup\$ Commented Oct 7, 2014 at 7:21
  • \$\begingroup\$ std::remove_if is not specific to C++11, though. \$\endgroup\$ Commented Oct 7, 2014 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.