2017-04-08 275 views
0

我试图解密一个句子。对于找到的每个单词,我都想将其添加到计数器中。我有一个嵌套for循环,当用户键入句子时,一个for循环将循环遍历句子(int i = 0),另一个(int j = 0)循环遍历数组,并且当它们找到相应的字母。我认为我所做的是有道理的,但由于某种原因,它不起作用。这里有一段代码处理本节。预先感谢您:)如何使用数组查找字符串中的字母C++

#include <iostream> 
#include <string> 
#include <cctype> 

using namespace std; 
string alphebet[26] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; 

string sentence; 
cin >> sentence; 
for(int i = 0; i < sentence.length(); i++){ 
    for(int j = 0; j < alphebet; j++){ 
     if (sentence[i] == alphebet[j]){ 
      counter_letters = counter_letters + 1; 
     } 
    } 
} 
+0

请检查[MCVE]。你的问题是什么? “它不工作”不通知,所以我们不能帮助。 –

+0

'j'从'0'到'alphabet',你可能想'0'到'26' – user463035818

+0

有一个'isupper'函数:https://linux.die.net/man/3/isupper – mch

回答

0

首先改变你的alphebet的字符数组像这样的char alphabet[26]。然后,您需要使用getline(cin, sentence)来获取像“Hello World”这样的整行输入,而cin << sentence只能得到第一个单词。接下来,您需要将字符串转换为大写,以便稍后与您的alphebet匹配,请使用transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper);执行此操作。之后,一定要初始化变量counter_letters。作为一个附注,你不需要做counter_letters = counter_letters + 1;你可以做counter_letters += 1;counter_letters++;++counter_letters;

#include <iostream> 
#include <string> 
#include <cctype> 
#include <algorithm> 

using namespace std; 
int main() { 
    char alphebet[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; 

    string sentence; 
    getline(cin,sentence); 
    transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper); 

    int counter_letters = 0; 
    for(int i = 0; i < sentence.length(); i++){ 
     for(int j = 0; j < 26; j++){ 
      if (sentence[i] == alphebet[j]){ 
       counter_letters++; 
      } 
     } 
    } 
    cout << counter_letters << endl; 
} 
+0

嘿如果我想使用“句子= toupper(句子);”......由于某种原因,toupper不会以这种方式工作......为什么? –

+0

int toupper(int c);'你使用错了,它接受一个单一的字符'int c'并返回一个int形式的另一个字符。 – chbchb55

+0

这就是为什么你必须使用'transform' – chbchb55

相关问题