c++ - 在 C++ 中拆分字符串(使用 cin)

标签 c++ string split cin

我在做THIS UVa 问题,它接受以下输入:

This is fun-
ny!  Mr.P and I've never seen
this ice-cream flavour
before.Crazy eh?
#
This is fun-
ny!  Mr.P and I've never seen
this ice-cream flavour
before.Crazy eh?
#

并产生这个输出:

1 1
2 3
3 2
4 3
5 3
6 1
7 1
8 1

1 1
2 3
3 2
4 3
5 3
6 1
7 1
8 1

在输入中,# 划分大小写。我应该获取每个单词的长度并计算每个不同长度的频率(如您在输出中看到的,长度为 1 的单词出现一次,长度 2 出现三次,长度 3 出现两次,依此类推)。

我的问题是:在 cin 中读取时,before.Crazy算作一个单词,因为没有空格将它们分开。然后它应该像在某些标点符号上拆分字符串一样简单(例如 {".",",","!","?"})...但是 C++ 似乎没有简单的方法来拆分字符串。

那么,我的问题是:如何拆分字符串并将每个返回的字符串发送到处理其余问题的函数?

这是我的代码:

int main()
{
    string input="";
    while(cin.peek()!=-1)
    {   
        while(cin >> input && input!="#")
        {
            lengthFrequency(input);
            cout << input << " " << input.length() << endl;
        }

        if(cin.peek()!=-1) cout << endl;
        lengthFrequencies.clear();
    }
    return 0;
}

lengthFrequencymap<int,int> .

最佳答案

您可以使用 std::locale 重新定义流认为是空白字符的内容自定义 std::ctype<char>方面。下面是相应的代码,它并没有完全完成分配,但演示了如何使用 facet:

#include <algorithm>
#include <iostream>
#include <locale>
#include <string>

struct ctype
    : std::ctype<char>
{
    typedef std::ctype<char> base;
    static base::mask const* make_table(char const* spaces,
                                        base::mask* table)
    {
        base::mask const* classic(base::classic_table());
        std::copy(classic, classic + base::table_size, table);
        for (; *spaces; ++spaces) {
            table[int(*spaces)] |= base::space;
        }
        return table;
    }
    ctype(char const* spaces)
        : base(make_table(spaces, table))
    {
    }
    base::mask table[base::table_size];
};

int main()
{
    std::cin.imbue(std::locale(std::locale(), new ctype(".,!?")));
    for (std::string s; std::cin >> s; ) {
        std::cout << "s='" << s << "'\n";
    }
}

关于c++ - 在 C++ 中拆分字符串(使用 cin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579390/

相关文章:

c++ - 色盲一个c++程序

c++ - 我们可以继承自 Qt 容器吗?

Java如何保留从String到JLabel的换行符?

c - 为什么 str1==str2 "equal"?

c++ - 通过 int 检索可变参数类的给定成员

c++ - DLL加载和系统镜像空间

c++ - 在 C++ 中通过正则表达式搜索(大)文件

c - C 中使用分隔符分割字符串

javascript - 突出显示字符串中的文本

javascript - 类型错误:未定义不是对象 string.split .split