Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

small string challenge

Name: Anonymous 2012-05-04 10:39

hi /prog/

I need to make a function that takes two strings, and removes all characters from the first string that are in the second string; we get marked on how efficient our code is. This is what I got so far, it's pretty shit and apparently theres a much better way to do it.


#include <iostream>
#include <string.h>

void rmFromString(std::string & toBeProcessed, const std::string & toBeIgnored)
{
        size_t found;
      std::string newString;

      found = toBeProcessed.find_first_not_of(toBeIgnored);

      while (found != std::string::npos)
      {
            newString += toBeProcessed[found];
            found = toBeProcessed.find_first_not_of(toBeIgnored, found + 1);
      }

    toBeProcessed = newString;

}

int main()
{
    std::string toBeProcessed = "she sells sea shells on the sea shore",
        toBeIgnored = "se";

    rmFromString(toBeProcessed, toBeIgnored);

    std::cout << toBeProcessed << std::endl;
}


anyone want to point me in the right direction?

Name: Anonymous 2012-05-04 22:52

>>7
You should use unsigned for table indices. Otherwise sign extension will fuck you up.

Here's a solution that gets rid of the condition in the main loop, only inline asm can be more efficient.

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

int table[256];

int main(int argc, char **argv)
{
    unsigned int i, j;
    char *out, *pout;

    if (argc < 3)
        return 1;

    for (i = 0; i<256; ++i)
        table[i] = 1;
    for (i = 0; argv[2][i]; ++i)
        table[(unsigned int)argv[2][i]]--;
    out = malloc(strlen(argv[1]) + 1);
    for (pout=out,i=0; argv[1][i]; ++i) {
        j = argv[1][i];
        *pout = j;
        pout += table[j];
    }
    out[j] = 0;
    puts(out);
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List