简体   繁体   English

比较字符串中的各个字符。 在用户输入的字母字符串中查找辅音

[英]Comparing individual characters in a string. Finding Consonants in a user input string of letters

I've been tasked to write code for a c++ program that will find the consonants in user input. 我的任务是为C ++程序编写代码,该程序将在用户输入中找到辅音。 So, if I enter abc, the program will tell me that there are two consonants. 因此,如果输入abc,程序将告诉我有两个辅音。 The question is below. 问题在下面。 I'm not looking for someone to write the code for me, I just need someone to help me figure out how to compare user input characters to a string. 我不是在寻找有人为我编写代码,我只是需要有人帮助我弄清楚如何将用户输入的字符与字符串进行比较。

Write a program that determines how many consonants are in an entered string of 50 characters or less. 编写一个程序,确定输入的50个字符或更少的字符串中有多少个辅音。 Output the entered string and the number of consonants in the string. 输出输入的字符串和该字符串中的辅音数量。 You can assume the following ; 您可以假设以下内容: Consonants: bcdfghjklmnpqrstvwxyz 辅音:bcdfghjklmnpqrstvwxyz

Define a string with all consonants: 用所有辅音定义一个字符串:

string cons = "bcd" // etc

Put your actual sting to lower case, if needed 如果需要,将您的实际值小写

std::transform(str.begin(), str.end(), str.begin(), ::tolower);

Next, itearete through your string characters and try to find this character in the consonant string. 接下来,反复检查您的字符串字符,并尝试在辅音字符串中找到该字符。

int consonants = 0;
for (string::iterator i = str.begin(); i !< str.end(); ++i)
   if (cons.find(*i) != string::npos)
      ++consonants;

Or, if you are sure that your string will only contains characters from az, use vowels as suggested below: 或者,如果您确定您的字符串仅包含来自z的字符,请按照以下建议使用元音:

 string vow = "aei" // etc
 //...
 int consonants = 0;
 for (string::iterator i = str.begin(); i !< str.end(); ++i)
    if (vow.find(*i) == string::npos)
       ++consonants; 

This may not be the most efficient method, but since you're only dealing with strings of less than 50 characters, it's not a big deal. 这可能不是最有效的方法,但是由于您只处理少于50个字符的字符串,所以没什么大不了的。

Here's the pseudocode: 这是伪代码:

Create a string containing all of the consonants as you listed above.
Prompt user for input
Store the input in a string
Use a loop to iterate through each character of the input string
    Use another loop to check each character against your string of consonants
        If it matches a consonant, increment your counter
Output the input string and count

If you're using C++ strings, you'll use the string length in your loop stopping condition. 如果使用的是C ++字符串,则将在循环停止条件中使用字符串长度。 If you're using C strings, you'll use the null byte in your loop stopping condition. 如果使用的是C字符串,则将在循环停止条件中使用空字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM