简体   繁体   English

C++ - 如何在字符串中查找(变量)字符?

[英]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.我需要在 for 循环中查找用户输入的字符。 I'd usually do我通常会这样做

  • if (sentence[i] == 'e')如果(句子[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.但因为在这里,'e' 将是一个单字母字符变量,我不知道如何比较该值。 I can't just enter我不能只是进入

  • if (sentence[i] == thechar)如果(句子[i] == thechar)

but I also can't create a variable to contain the character in between quotation marks like但我也无法创建一个变量来包含引号之间的字符,例如

  • char2 = "\\'" + thechar + "\\'"; 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.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.有关更多信息,请访问http://www.cplusplus.com/reference/string/string/find/页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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