简体   繁体   中英

C++ - How to find a (variable) character in a string?

I'm required to find a character entered by the user in a for loop. I'd usually do

  • if (sentence[i] == 'e')

but since here, 'e' will be a one letter char variable, I don't know how to get that value to be compared. I can't just enter

  • if (sentence[i] == thechar)

but I also can't create a variable to contain the character in between quotation marks like

  • char2 = "\\'" + thechar + "\\'";

So how do I do it in this context? I'm not allowed to use other, more effective, more advanced methods. This is a basics course. Please help!

string word;
char letter;
cout << "Enter a word\n";
cin >> word;
cout << "What letter would you like to search for?\n";
cin >> letter;
for (int i = 0; i < word.length(); i++)
{
    if (word[i] == letter)
    {
        cout << letter << " is the " << i + 1 << "character of " << word << endl;
    }
}

You can create a variable where you ask for the letter the user wants, and use that variable to compare.

To find position of chosen letter you can use std::string.find(...)

std::string str = "My house is white.";
std::size_t pos = str.find('s');
std::cout << "Position: " << pos << std::endl;

Output:

Position: 6

For more informations go to http://www.cplusplus.com/reference/string/string/find/ page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM