0

Lets say that we have a specific string:

string a[]={"ab","cd","ef"}

and we want a specific string when we input first character of the string: for example:

input: c
output: "cd"

what i was thinking is that:

so let's say we assign char x for the input value. and then using the loop to go through the list, but i'm stuck of how char x is going to stop the loop and printing the specific string.

other question is how its going to be different to find a letter thats inside the string. for example inputing: d and output: "cd"

M W
  • 67
  • 2
  • 8
  • A good data structure for the first problem (prefix search) is a search trie (e.g. http://stackoverflow.com/questions/1036504/trie-implementation). But if the number of strings is small, just looping and performing string comparison should be fine. – jogojapan Sep 19 '12 at 00:23

1 Answers1

2

I will answer both of your questions (even though you should keep it to one question per "question").

To stop a loop you use the break statement.

To find a character (or a string) in a string you use the std::string::find function.

Now combining them:

#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    std::string a[] = { "ab", "cd", "ef", "ce" };

    char x;
    std::cout << "Enter a letter: ";
    std::cin >> x;

    // If you want to stop as soon as you find a string with the letter
    // you have to loop manually
    std::cout << "\nFind first string containing letter:\n";
    for (std::string s : a)
    {
        if (s.find(x) != std::string::npos)
        {
            std::cout << "Letter '" << x << "' found in string \"" << s << "\"\n";
            break;  // Stop the loop
        }
    }

    // If you want to print all strings containing the letter you can
    // use the `std::for_each` function
    std::cout << "\nFind all strings containing letter:\n";
    std::for_each(std::begin(a), std:end(a), [x](const std::string &s) {
           if (s.find(x) != std::string::npos)
               std::cout << "Letter '" << x << "' found in string \"" << s << "\"\n";
        });
}

Note: The above code contains two features from the "new" C++11 standard: Range-based for-loops; And lambda functions.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621