3 Write a c++program that reads in a search word then reads in several words ending with a character The program should count how many times the search word occurs in the text Assume that there is
- Solution:
#include
using namespace std;
int main() { char search_word[20], word[20]; int count = 0;
cout << "Enter the search word: ";
cin >> search_word;
cout << "Enter some words (end with *): ";
while (cin >> word)
{
if (word[strlen(word) - 1] == '*')
{
word[strlen(word) - 1] = '\0';
if (strcmp(word, search_word) == 0)
count++;
break;
}
else
{
if (strcmp(word, search_word) == 0)
count++;
}
}
cout << "The word " << search_word << " appeared " << count << " times." << endl;
return 0;
}
- Solution:
#include
using namespace std;
int main() { char search_word[20], word[20]; int count = 0;
cout << "Enter the search word: ";
cin >> search_word;
cout << "Enter some words (end with *): ";
while (cin >> word)
{
if (word[strlen(word) - 1] == '*')
{
word[strlen(word) - 1] = '\0';
if (strcasecmp(word, search_word) == 0)
count++;
break;
}
else
{
int len = strlen(word);
if (ispunct(word[len - 1]))
word[len - 1] = '\0';
if (strcasecmp(word, search_word) == 0)
count++;
}
}
cout << "The word " << search_word << " appeared " << count << " times." << endl;
return 0;
原文地址: https://www.cveoy.top/t/topic/hw48 著作权归作者所有。请勿转载和采集!