我找到字母最少的代码是:
cin.get(a, 100);
p = strtok(a," ");
min = p;
int ok;
while (p) {
if (strlen(min) > strlen(p)) {
strcpy(min, p);
}
p = strtok(NULL," ");
}
cout << "The word with the fewest lettes is " << min << endl;
我的问题是如何找到出现的次数? 对不起,如果这是一个愚蠢的问题,我是c ++的初学者。
答案 0 :(得分:1)
只需添加一个简单的计数器变量,该变量在开头为0,当有一个字符较少的字符时更改为1;如果存在与具有最少字符的单词具有相同字符数的单词,则增加。< / p>
我认为这样的事情会起作用。
enter code herecin.get(a, 100);
p = strtok(a," ");
min = p;
int ok;
int counter = 0;
while (p) {
if (strlen(min) > strlen(p)) {
strcpy(min, p);
counter = 1;
}
else if(strlen(min) == strlen(p)){
counter++;
}
p = strtok(NULL," ");
}
答案 1 :(得分:0)
使用std::string
的简单快速的解决方案。您可以阅读std::string
here。它是标准库附带的强大课程,如果你掌握了它,你的生活将变得更加容易。 std::size_t
#include <iostream>
#include <string>
int main ()
{
std::string input;
std::cin >> input;
std::size_t curPos = 0;
std::size_t length = input.length();
std::size_t sw_offset = 0; // sw means 'shortest word'
std::size_t sw_length = 0;
std::size_t sw_count = 0;
while(curPos <= length)
{
std::size_t newPos = input.find_first_of(' ', curPos);
if(newPos == std::string::npos) // If there is no whitespace it means it's only 1 word
newPos = length;
if(newPos != curPos) // If word isn't empty (currentWordLength > 0)
{
std::size_t currentWordLength = newPos - curPos;
if(!sw_length || sw_length > currentWordLength)
{
sw_offset = curPos; // Store offset and length instead of copying
sw_length = currentWordLength;
sw_count = 1;
}
else if(sw_length == currentWordLength &&
input.substr(sw_offset, sw_length) == input.substr(curPos, currentWordLength))
{
++sw_count;
}
}
curPos = newPos + 1;
}
std::cout << "Fewest letter word is " << input.substr(sw_offset, sw_length)
<< " and it's appeared " << sw_count << " time(s)" << std::endl;
}
的优点
#include <iostream>
#include <cstring>
#include <algorithm>
int main ()
{
char input[256];
std::cin.get(input, sizeof(input));
std::size_t curPos = 0;
std::size_t length = strlen(input);
std::size_t sw_offset = 0;
std::size_t sw_length = 0;
std::size_t sw_count = 0;
while(curPos <= length)
{
std::size_t newPos = std::find(input + curPos, &input[sizeof(input) - 1], ' ') - input;
std::size_t currentWordLength = newPos - curPos;
if(currentWordLength > 0)
{
if(!sw_length || sw_length > currentWordLength)
{
sw_offset = curPos;
sw_length = currentWordLength;
sw_count = 1;
}
else if(sw_length == currentWordLength &&
strncmp(input + sw_offset, input + curPos, currentWordLength) == 0)
{
++sw_count;
}
}
curPos = newPos + 1;
}
char result[256];
strncpy(result, input + sw_offset, sw_length);
std::cout << "Fewest letter word is " << result
<< " and it's appeared " << sw_count << " time(s)" << std::endl;
}
c样式字符串相同
{{1}}