如何改进我的代码以正确计数唯一行? [英] How to improve my code to correctly count unique lines?

查看:52
本文介绍了如何改进我的代码以正确计数唯一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写代码以查找唯一的行以及唯一的单词.我在下面尝试了用于唯一行的代码,但是在涉及唯一行时,它无法正确计算.我相信它会忽略输入,仍在计算包含字母,单词,句子等的行.因此,在确定添加内容时,我需要帮助,它将输入(空白行)视为行,而不计算任何多余的行相同的.我知道这种情况正在发生,因为我已经测试了一些不同的行.至于独特的词,我什至不知道该如何开始:/

I am currently trying to write code for finding unique lines as well as unique words. I have my attempted code below for unique lines but it is not calculating correctly when it comes to unique lines. I believe it is ignoring enters and still counting lines that contain letters, words, sentences, etc. So I need help in figuring out what to add that it will count enters (blank lines) as lines and not count any extra lines that are the same. I know this is happening because I have tested a few different lines. As for the unique words, I don't even know how to get started :/

unsigned long countULines(const string& s)
{
   set<string> wl;
   string ulines;
   for(int ul = 0; ul < s.size(); ul++){
      wl.insert(ulines);
   }
   return wl.size();
}

推荐答案

这将为您工作:

#include <iostream>
#include <sstream>
#include <string>
#include <set>

size_t countUniqueLines(const std::string& s)
{
    std::set<std::string> uniqueLines;
    std::istringstream is(s);

    std::string line;
    while (std::getline(is, line)) {
        if (!line.empty() && line[line.size() - 1] == '\r') {       
          line.erase(line.size() -1);
        }
        uniqueLines.insert(line);
    }

    return uniqueLines.size();
}

int main()
{
    const std::string myLines = "four\none\n\ntwo\nthree\nthree\n\n";

    std::cout << countUniqueLines(myLines) << std::endl;
}

这篇关于如何改进我的代码以正确计数唯一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆