Remove a list of characters from a char array/string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • samaresh4
    New Member
    • Feb 2017
    • 1

    Remove a list of characters from a char array/string

    I am looking for a more efficient version than the following to remove a list of characters from a char array or string.

    CODE

    #include <iostream>
    #include <cstring>

    using namespace std;

    int main(int argc, char* argv[]) {

    char str[] = "table+chair%fu rniture-futon#bed";
    char *t = "+*-/%#";
    char *pr = str;

    int i = 0;
    while(*pr != '\0') {
    //if(*pr != t) {
    if(strchr(t,*pr ) == NULL) {
    str[i] = *pr;
    ++i;
    }
    pr++;
    }
    str[i]='\0';

    cout << strlen(str) << ":" << str << endl;

    return 0;

    }

    /CODE
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Try strcpy.

    strcpy takes a char* argument for where the copy is to go. In your case that would be the address of the last char to be deleted +1.

    strcpy will now copy the rest of your original string on top of the sequence you are deleting and the copy stops at the \0 of the original string.

    What do you think?

    Comment

    Working...