C\C++ string – remove extra spaces simple code

prog-languages

this is a simple c / c++ code that receives a string and then generates a new one, with no extra spaces in the middle, begin and end of the string.

std::string remove_extra_spaces (std::string str) {
        char str_tmp[str.size()+1];
        std::size_t ptr1,ptr2;
        bool prev_char_is_space = true;
        ptr1 = ptr2 = 0;
        for (; ptr1<str.size(); ptr1++) {
                if (str[ptr1] == ' ' && prev_char_is_space)
                        continue;
                str_tmp[ptr2++] = str[ptr1];
                prev_char_is_space = false;
                if (str[ptr1] == ' ') prev_char_is_space = true;
        }
        do {
                str_tmp[ptr2] = '\0';
                if (ptr2 == 0) break;
                ptr2 -=1 ;
        } while (str_tmp[ptr2] == ' ');
        return std::string(str_tmp);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Watch Dragon ball super