0

say i have the following:

string myArray[] = { "adam", "aaron", "brad", "brandon" };

cout << "Please type a name: ";

i want it so when a user types "bra" and hits enter, the program returns

brad
brandon

if the user types "a", the program returns

adam
aaron

if the user types "adam", the program returns

adam

I have tried strstr, mystring.compare(str), mystring.compare(x, n, str) - i can't find anything that is working.

what function would be the best way of handling this operation?

1
  • You said you've tried various things but you haven't actually shown why they don't work, your issue is probably in how you are attempting to use those functions. Commented Jan 30, 2015 at 2:54

2 Answers 2

2

This is a great time for lambdas and std::copy_if. Assuming the string you want to find is named to_find:

std::copy_if(std::begin(myArray), std::end(myArray),
             std::ostream_iterator<std::string>(std::cout, "\n"),
             [&](const std::string& s){
                 return s.find(to_find) == 0;
             });

Specifically, the way to test if some string a contains another string b, we can do:

a.find(b) == 0

std::string::find returns the index at which b is found, or npos if it's not found. We want 0, since you only want prefixes. We then wrap that in a lambda and pass it into copy_if, which will copy every element which passes our predicate and writes it to the output iterator we provide - in this case an ostream_iterator<std::string> which writes to std::cout and uses \n' as a delimeter.

To write out the same without C+11 would look something like:

const size_t size = sizeof(myArray) / sizeof(*myArray);
for (size_t i = 0; i < size; ++i) {
    if (myArray[i].find(to_find) == 0) {
        std::cout << myArray[i] << std::endl;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

do i need a certain header for this?
@user3571392 Check out the references I linked to, it's a good site to familiarize yourself with. For your specific question: you'll need <algorithm> and <iterator>
0

Depending on how big your list of names is going to be, it can quickly become very slow to scan through the whole thing. You might want to look into implementing your own prefix tree (aka trie).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.