-1

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.

4
  • 3
    What is an "empty character?" Feb 13, 2014 at 18:57
  • @Angew A removed one ;) ... Feb 13, 2014 at 19:16
  • @jrd1 No, it's not a dupe (especially not concerning the accepted answer there)! There's no need for 'shrinking' or dynamically resizing the array, see my answer & more comments downwards ... Feb 14, 2014 at 0:22
  • @user3215228 Please note my additional recommendations about real c++ implementations. Feb 14, 2014 at 1:10

5 Answers 5

0

There is no such thing as an empty character.

If you mean a space then change '' to ' ' (with a space in it).

If you mean NUL then change it to '\0'.

5
  • No i dont mean null character , I just want spaces and punctuation marks to be replaced with empty spaces. Feb 13, 2014 at 19:01
  • @user3215228 What is an "empty space?" Do you mean the space character? Or do you actually want to remove the spaces and punctuations from the string? Feb 13, 2014 at 19:02
  • Do you mean you want to remove those characters? You can't do that by assigning them a value. You need to shift all the characters in the string after that position back one position or something.
    – Paul
    Feb 13, 2014 at 19:04
  • for eg the word is str,, ing, output should be string Feb 13, 2014 at 19:04
  • @user3215228 As paulpro mentioned you want to remove the characters. That's a completely different operation, I recommend to use std::string for doing this, otherwise copy the rest of the string to the location where you found one of your characters in question. Feb 13, 2014 at 19:07
0

Edit: the answer is no longer relevant now that the OP has edited the question. Leaving up for posterity's sake.

If you're wanting to add a null character, use '\0'. If you're wanting to use a different character, using the appropriate character for that. You can't assign it nothing. That's meaningless. That's like saying

int myHexInt = 0x;

or

long long myIndeger = L;

The compiler will error. Put in the value you wanted. In the char case, that's a value from 0 to 255.

5
  • No i dont mean null character , I just want spaces and punctuation marks to be replaced with empty spaces. Feb 13, 2014 at 19:02
  • Okay, well use a space character, then. str1[start]=' '; Just don't try to assign a character to nothing. That's like saying int x = ; and hoping it compiles.
    – m24p
    Feb 13, 2014 at 19:04
  • @m24p The OP want's to replace space char with space char?? Feb 13, 2014 at 19:09
  • I thought the "isspace" function was be checking for all types of whitespace, eg tab characters etc. The OP has since made it clear the real question should be how to remove characters.
    – m24p
    Feb 13, 2014 at 19:12
  • @m24p I've been clarifying, but doesn't matter ... Feb 13, 2014 at 19:35
0

UPDATE:

From the edit to OP's question, it's apparent that he/she wanted to trim a string of punctuation and space characters.

As detailed in the flagged possible duplicate, one way is to use remove_copy_if:

string test = "THisisa test;;';';';";
string temp, finalresult;

remove_copy_if(test.begin(), test.end(), std::back_inserter(temp), ptr_fun<int, int>(&ispunct));
remove_copy_if(temp.begin(), temp.end(), std::back_inserter(finalresult), ptr_fun<int, int>(&isspace));

ORIGINAL

Examining your question, replacing spaces with spaces is redundant, so you really need to figure out how to replace punctuation characters with spaces. You can do so using a comparison function (by wrapping std::ispunct) in tandem with std::replace_if from the STL:

#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
using namespace std;

bool is_punct(const char& c) {
    return ispunct(c);
}

int main() {
    string test = "THisisa test;;';';';";
    char test2[] = "THisisa test;;';';'; another";

    size_t size = sizeof(test2)/sizeof(test2[0]);

    replace_if(test.begin(), test.end(), is_punct, ' ');//for C++ strings
    replace_if(&test2[0], &test2[size-1], is_punct, ' ');//for c-strings

    cout << test << endl;
    cout << test2 << endl;
}

This outputs:

THisisa test
THisisa test         another
5
  • To the downvoter, was there something that could be improved upon? If so, I'd welcome any feedback.
    – jrd1
    Feb 13, 2014 at 19:46
  • @πάνταῥεῖ: No problem. It's an honest mistake: these things do happen.
    – jrd1
    Feb 13, 2014 at 19:59
  • 'To the downvoter ..' Sorry, wasn't a mistake: The question asks for removing that characters, not replacing by spaces ('\0x32')! You'd better mentioned std::remove_if ... Feb 13, 2014 at 20:02
  • @πάνταῥεῖ: I only now saw that edit: I'm working on it. Thanks!
    – jrd1
    Feb 13, 2014 at 20:04
  • It's not a duplicate for this question, at least the accepted answer doesn't apply ... Feb 13, 2014 at 21:15
-1

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.

11
  • 1
    I'm not the downvoter, but I can conjecture that it may have something to do with this answer: stackoverflow.com/a/6987247/866930.
    – jrd1
    Feb 13, 2014 at 19:52
  • What's bad with using strncpy() in c++?? I have many situations, where I simply can't afford the conveniences and usage of std::string ... Feb 13, 2014 at 20:10
  • Your use of remove_if on the C-String is completely wrong as remove_if won't remove the characters from a statically allocated array, but only keep the contents in memory unreplaced in the remainder of the string.
    – jrd1
    Feb 13, 2014 at 20:33
  • @jrd1 At least this works fine?? It doesn't matter if the array is statically allocated or not IMHO (did you mean const inputs??)! Feb 13, 2014 at 20:37
  • 1
    Hadn't seen remove_if before. Seems cool. Still, I find my c-style answer more readable. Feb 13, 2014 at 20:58
-1

As I don't like the accepted answer, here's mine:

#include <stdio.h>
#include <string.h>
#include <cctype>

int main() {
    char str[100] = "str,, ing";
    int bad = 0;
    int cur = 0;
    while (str[cur] != '\0') {
        if (bad < cur && !ispunct(str[cur]) && !isspace(str[cur])) {
                str[bad] = str[cur];
        }
        if (ispunct(str[cur]) || isspace(str[cur])) {
            cur++;
        }
        else {
            cur++;
            bad++;
        }
    }
    str[bad] = '\0';
    fprintf(stdout, "cur = %d; bad = %d; str = %s\n", cur, bad, str);
    return 0;
}

Which outputs cur = 18; bad = 14; str = string

This has the advantage of being more efficient and more readable, hm, well, in a style I happen to like better (see comments for a lengthy debate / explanation).

13
  • Yes, after fixing your code a bit it works fine and is more efficient (at least vs. the strncpy() version). It would be nice to have a confirmation, that the remove_if() sample really is less efficient as what's given from your answer. Feb 13, 2014 at 21:02
  • 1
    @πάνταῥεῖ Yes, your code really truly is significantly less efficient. About 16 times less efficient (on my machine). I've just been bench-marking each. Feel free to duplicate my findings. Feb 13, 2014 at 21:30
  • Good point, then! Could you show a bit more about your benchmarking methods? I'm concerned, since remove_if() could be easily implemented in a similar manner as you did, and I usually assume that the standard implementations are as efficient as ever possible to cover the applicable use cases. Sadly, that might not be true for all compiler and c++ standard library implementations! Feb 13, 2014 at 21:37
  • The bench-mark simply uses the top answer's method to time a loop of 10000000 iterations of each method with the string "str,, ing". Feb 13, 2014 at 21:43
  • 1
    FWIW my C-style solution would be like char *dst = str, *src = str; while (*src) { if !ispunct(*src) && !isspace(*src) { *dst++ = *src; } ++src; } *dst = 0;. And that's almost exactly what remove_if will do if you can get everything properly inlined, except that of course it doesn't know about nul terminated strings. Feb 13, 2014 at 23:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.