我已經設法在字串的任何位置獲取用戶輸入字符的計數,但是我將如何僅計算以用戶輸入字符開頭的單詞?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string main;
char charr;
cout << "Enter the main string : "<<endl;
getline(cin,main);
cout << "Enter a character: "<<endl;
cin >> charr;
int count = 0;
for (int i = 0; i < main.size(); i )
if (main[i] == charr)
count ;
cout << count << endl;
}
uj5u.com熱心網友回復:
您可以將std::stringastd::istringstream然后放入std::count_if以輸入字符開頭的單詞。
它可能看起來像這樣:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
int main() {
std::string main;
char charr;
std::cout << "Enter the main string:\n";
std::getline(std::cin, main);
std::cout << "Enter a character:\n";
if(not (std::cin >> charr)) return 1;
std::istringstream is(main); // put the main string in an istringstream
// count words starting with charr:
auto count = std::count_if(std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>{},
[charr](const std::string& word) {
return word.front() == charr;
});
std::cout << count << '\n';
}
uj5u.com熱心網友回復:
std::stringstream ss;
ss << main;
string word;
while(ss >> word)
{
if(word[0] == charr)
count;
}
編輯:使用 Ted Lyngmo 的評論進行更正。謝謝。
uj5u.com熱心網友回復:
在您的示例中,您無法確保在被檢查的字符之前的字符是空格。這樣做,你的方法就會奏效。你不想知道有多少個字符匹配charr,你想知道有多少個單詞開頭 charr。要從整個 中計算std::string,您需要檢查前一個字符是否為空格。
cctype您可以通過包含和使用isspace()宏輕松檢查前一個字符是否為空格。
此外,您必須驗證每個用戶輸入。用戶可以生成手冊EOF以取消作為有效用戶動作的輸入。(Ctrl d或Ctrl z在窗戶上)。
一個簡短的例子,使用你的 read with getline(),洗掉using namespace std;并為你的字串選擇一個新名稱(line而不是main)將是:
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string line {};
char charr = 0;
int count = 0, last = 0;
std::cout << "Enter the main string : ";
/* validate read and line not empty */
if (!getline(std::cin, line) || line.size() == 0) {
return 0;
}
std::cout << "Enter a character: ";
if (!(std::cin >> charr)) { /* validate read */
return 0;
}
if (line[0] == charr) { /* check 1st char */
count ; /* increment on match */
}
last = line[0]; /* set last char seen */
for (size_t i = 1; i < line.size(); i ) { /* loop 1 to end */
/* last is space and current is charr */
if (isspace(last) && line[i] == charr) {
count ; /* increment count */
}
last = line[i]; /* set last char seen */
}
std::cout << count << '\n'; /* output results */
}
(注意:雖然using namespace std;對于小型示例程式可能很好且方便,請參閱:為什么“使用命名空間 std;”被認為是不好的做法?)
示例使用/輸出
$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: h
2
或者
$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: n
1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484064.html
標籤:C
