【发布时间】:2021-11-01 06:05:28
【问题描述】:
我正在尝试从段落中找出句子中的最大单词数(用点分隔)。我完全陷入了如何排序和输出到标准输出。
例如: 给定一个字符串 S: {"Program to split strings. By using custom split function. In C++"};
预期的输出应该是:5
#define max 8 // define the max string
string strings[max]; // define max string
string words[max];
int count = 0;
void split (string str, char seperator) // custom split() function
{
int currIndex = 0, i = 0;
int startIndex = 0, endIndex = 0;
while (i <= str.size())
{
if (str[i] == seperator || i == str.size())
{
endIndex = i;
string subStr = "";
subStr.append(str, startIndex, endIndex - startIndex);
strings[currIndex] = subStr;
currIndex += 1;
startIndex = endIndex + 1;
}
i++;
}
}
void countWords(string str) // Count The words
{
int count = 0, i;
for (i = 0; str[i] != '\0';i++)
{
if (str[i] == ' ')
count++;
}
cout << "\n- Number of words in the string are: " << count +1 <<" -";
}
//Sort the array in descending order by the number of words
void sortByWordNumber(int num[30])
{
/* CODE str::sort? std::*/
}
int main()
{
string str = "Program to split strings. By using custom split function. In C++";
char seperator = '.'; // dot
int numberOfWords;
split(str, seperator);
cout <<" The split string is: ";
for (int i = 0; i < max; i++)
{
cout << "\n initial array index: " << i << " " << strings[i];
countWords(strings[i]);
}
return 0;
}
countWords() 中的 Count + 1 仅在第一个结果中正确给出数字,然后将 " " 空格添加到字数统计中。
请先考虑用最容易理解的解决方案来回答。 (std::sort, 创建一个新函数, lambda)
【问题讨论】:
-
你要排序什么?你的任务是找出句子中的最大单词数。
-
点之间总是有一个词吗?如果是这样,那么最简单的方法不是计算点数并加1吗?样本测试数据是什么样的?
-
int len(string str) // length of the string-std::string有一个名为size()的成员函数,您可以调用它来获取字符串的长度。还有一个叫length()返回同样的东西。所以,不要使用len(str),而是使用str.size() -
请显示minimal reproducible example 的输入、预期和实际输出
-
@MpcHAG 另外,
std::string数组的用途是什么?除非您想实际存储句子单词以供以后使用,否则解决方案中不需要它们。这可能是让其他人对您想要输出的内容感到困惑的原因,因为您想要输出的只是最大数量,而不是实际使用的单词。请查看使用std::stringstream,您将看到与您现在所拥有的相比,该解决方案实际上会清洁多少。
标签: c++ string sorting max std