2014-07-25 55 views
0

我需要在for循环中找到由用户输入的字符。我通常会做C++ - 如何查找字符串中的(变量)字符?

  • 如果(全文[I] == 'E')

但因为在这里, 'E' 将是一个字母字符变量,我不知道如何以获得该价值进行比较。我不能只是进入

  • 如果(全文[I] == thechar)

,但我也不能创建一个变量包含的字符在引号之间像

  • char2 =“\'”+ thechar +“\'”;

那么在这种情况下我该怎么做呢?我不允许使用其他更有效,更高级的方法。这是一门基础课程。请帮忙!

+0

*我需要找到一个字符* - 引号中的某个字符不是字符。 – chris

+0

'char c ='e'有什么问题; if(c == sentence [i]){/*...*/}'? – user3553031

+0

它可能不是'e'。我必须cin >> thechar。因此,如果用户输入u,我的条件将不得不检查'u',但我不知道如何创建一个将字符串u转换为字符串'u'的变量。我没有收到{/*...*/}部分。 – blue0

回答

3
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; 
    } 
} 

您可以创建一个变量,用于询问用户想要的字母,然后使用该变量进行比较。

+0

非常感谢。我所教的只是将字符串声明为char word [maxwordlength];所以我试图这样工作。最后,与其他语言几乎完全相同。 – blue0

1

要了解所选字母的位置,你可以使用std::string.find(...)

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

输出:

Position: 6 

欲了解更多信息请访问http://www.cplusplus.com/reference/string/string/find/页。