Search code examples
c++stringcstring

Remove character from array where spaces and punctuation marks are found


In my program, I am checking whole cstring, if any spaces or punctuation marks are found, just add empty character to that location but the complilor is giving me an error: empty character constant.

Please help me out, in my loop i am checking like this

if(ispunct(str1[start])) {
    str1[start]=''; // << empty character constant. 
}
if(isspace(str1[start])) {
    str1[start]=''; // << empty character constant. 
}

This is where my errors are please correct me.

for eg the word is str,, ing, output should be string.


Solution

  • Try this (as you asked for cstring explicitly):

    char str1[100] = "str,, ing";
    
    if(ispunct(str1[start]) || isspace(str1[start])) {
        strncpy(str1 + start, str1 + start + 1, strlen(str1) - start + 1);
    }
    

    Well, doing this just in pure language, there are more efficient solutions (have a look at @MichaelPlotke's answer for details).

    But as you also explicitly ask for , I'd recommend a solution as follows:

    Note you can use the standard c++ algorithms for 'plain' c-style character arrays also. You just have to place your predicate conditions for removal into a small helper functor and use it with the std::remove_if() algorithm:

    struct is_char_category_in_question {
        bool operator()(const char& c) const;
    };
    

    And later use it like:

    #include <string>
    #include <algorithm>
    #include <iostream>
    #include <cctype>
    #include <cstring>
    
    // Best chance to have the predicate elided to be inlined, when writing 
    // the functor like this:
    struct is_char_category_in_question {
        bool operator()(const char& c) const {
            return std::ispunct(c) || std::isspace(c);
        }
    };
    
    int main() {
        static char str1[100] = "str,, ing";
        size_t size = strlen(str1);
    
        // Using std::remove_if() is likely to provide the best balance from perfor-
        // mance  and code size efficiency you can expect from your compiler 
        // implementation.
        std::remove_if(&str1[0], &str1[size + 1], is_char_category_in_question());
    
        // Regarding specification of the range definitions end of the above state-
        // ment, note we have to add 1 to the strlen() calculated size, to catch the 
        // closing `\0` character of the c-style string being copied correctly and
        // terminate the result as well!
    
        std::cout << str1 << endl; // Prints: string
    }
    

    See this compilable and working sample also here.