[英]Searching for a specific char in a array of strings in c++
用戶必須輸入 3 個字符串,我們必須將它們放入一個數組中。 然后用戶輸入一個他想在輸入字符串中找到的字符。 然后,如果找到 char,則更新計數器 char 出現的次數。
例子:
用戶輸入字符串: Cat Car Watch
用戶字符輸入: a
結果:
Letter a appears 3 times!
如何搜索這樣的字符串數組以查找特定字符?
下面的代碼,但我被卡住了:
string userString[3];
for (int i = 0; i < 3; i++)
{
cout << "Input string: ";
getline(cin, userString[i]);
}
char userChar;
cout << "Input char you want to find in strings: ";
cin >> userChar;
int counter = 0;
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
cout << "The char you have entered has appeared " << counter << " times in string array!";
與其手動編寫 for 循環,不如使用標准算法,例如std::count
。
這是一個演示程序
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = 0;
for ( const auto &s : words )
{
count += std::count( std::begin( s ), std::end( s ), c );
}
std::cout << "count = " << count << '\n';
}
程序輸出為
count = 3
如果您的編譯器支持 C++ 20,那么您可以按以下方式編寫程序
#include <iostream>
#include <string>
#include <iterator>
#include <ranges>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = std::ranges::count( words | std::ranges::views::join, c );
std::cout << "count = " << count << '\n';
}
程序輸出再次是
count = 3
至於你的代碼,那么這個代碼片段
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
是不正確的。 您需要一個內部 for 循環來遍歷每個字符串,例如
for (int i = 0; i < 3; i++)
{
for ( char c : userString[i] )
{
if ( c == userChar)
{
counter++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.