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: 10 2012-05-05 17:40

>>11
Moi, j'utilise UTF-8 pour écrire le français.

Keep in mind that we're passing strings from the command line; few if any are going to be longer than 256. It's an assumption I should have made explicit, but I think it's a fair one.

Half-assed Informal testing with the input provided in >>1 suggests the putchar way (with the branch) is faster than the malloc way, so in light of >>15, I'd like to propose the following as our final result:

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

int table[UCHAR_MAX + 1];

int main(int argc, char **argv)
{
    if (argc != 3)
        return EXIT_FAILURE;

    for (; *argv[2]; ++argv[2])
        table[(unsigned int)*argv[2]] = 1;

    for (; *argv[1]; ++argv[1])
        if (!table[(unsigned char)*argv[1]])
            putchar(*argv[1]);

    putchar('\n');
    return EXIT_SUCCESS;
}


The advantage of this over x86 assembly (aside from portability and readability) is that it's also perfectly valid Sepples, so >>1-kun can hand it in and get a pat on the head from his teacher. I hope he relays said pat to us here.

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