One option is std::copy_if to copy the good characters to a return buffer:
char *trim(const char *str) {
std::size_t len = strlen(str);
char *ret = new char[len + 1]{}; //allocate space and initialize
std::copy_if(
str, //from beginning
std::find(str, str + len, ' '), //to first space (or end)
ret, //copy to beginning of buffer
isalnum //the alphanumeric characters
);
return ret; //return the buffer
}
int main() {
std::cout << trim("ab$#h%#.s354,.23nj%f abcsf"); //abhs35423njf
std::cout << trim("adua9d8f9hs.f,lere.r"); //adua9d8f9hsflerer
}
Notice how my example completely ignores the fact that you have to deallocate the memory you allocated in trim, which is ok in this case because the program ends right after. I strongly suggest you change it to use std::string instead. It both eases the definition of trim because of the std::begin and std::end compatibility, and manages the memory for you.