簡體   English   中英

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

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

我需要在 for 循環中查找用戶輸入的字符。 我通常會這樣做

  • 如果(句子[i] == 'e')

但因為在這里,'e' 將是一個單字母字符變量,我不知道如何比較該值。 我不能只是進入

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

但我也無法創建一個變量來包含引號之間的字符,例如

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

那么在這種情況下我該怎么做呢? 我不允許使用其他更有效、更高級的方法。 這是一門基礎課程。 請幫忙!

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

您可以創建一個變量,在其中詢問用戶想要的字母,然后使用該變量進行比較。

要查找所選字母的位置,您可以使用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/頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM