【问题标题】:Sorting Words from a input text depending on how many times it was repeated?根据重复次数对输入文本中的单词进行排序?
【发布时间】:2017-12-05 16:30:47
【问题描述】:

我正在尝试制作一个程序,该程序从用户那里读取输入文本,然后打印出每个单词以及它按排序顺序重复的次数。 (输入由空格分隔,可以包含标点符号但不能换行)

输入示例:我是一名优秀的程序员,我喜欢 C 语言

输出应该是:

  • a : 2 次
    我:1次
    上午 : 1 次
    好:1次

    ...等等。

** 对于输入,我使用了向量和类,但我不知道为什么我不能在其中推送多个项目。

class word {public:
word();
void set_data(string data_value);
void printing_data();
void counter_addition();
int count;
string data;};

int main(){ /*creating vecotr called items of list class type*/
vector<word>items;

/*creating a variable of list class type which is used to push data into the vector*/

word *element;

/*Reading the input text seperated by white spaces*/
int size = 0;
string text;

cout << "Enter the text: " << endl;
getline(cin, text);

size = text.length();
int left_space = -1;
int right_space = 0;
string Sub_String;

/*main loop for constructing substring of words and then manipulating them*/

for (int i = 0; i<size; i++)
{

    /*splitting the string into words*/
    if (isspace(text[i]) || ispunct(text[i]))
    {
        right_space = i;

        Sub_String = text.substr(left_space + 1, right_space - left_space - 1);
        /*for first word just push it*/

        if (left_space == -1)
        {
            element = new word();
            element->set_data(Sub_String);
            items.push_back(*element);

        }

        else
        {
            /*compare to vector's data */
            for (int j = 0; j < items.size(); j++)
            {
                if (Sub_String == items[j].data)
                {
                    items[j].count = items[j].count + 1;
                }
                else
                {
                    element = new word();
                    element->set_data(Sub_String);
                    items.push_back(*element);
                }

            }
        }
            left_space = right_space;
    }

如果单词相同,则输出正确。

输入:生活生活生活生活


输出:生命重复:4

请帮我解决这个问题,我是编程新手。

【问题讨论】:

  • 基本上,遍历每个单词(2 个 for 循环)并使用 (strcmp) 和递增计数器比较单词。也包括结构,因为它将使工作更容易存储字符串并在结构中重复,而不是每次都创建新变量。另外,因为您是编程新手,所以不要以效率为目标,而要以正确的代码为目标。所以将用户输入存储在一个文件中,因为它比使用子字符串更容易处理

标签: c++ class sorting vector


【解决方案1】:

将字符串值和计数存储到 std::map 并为每个单词检查它是否已经在映射中。如果存在,则增加计数。在相反的情况下,用 count = 1 插入它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2020-08-23
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多