且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串向量中的每个单词更改为大写

更新时间:2023-02-18 20:33:20

至少据我所知,这里的想法是忽略现有的行结构,每行写出 8 个单词,无论换行符如何输入数据.假设这是正确的,我将首先从输入中读取单词,而不注意现有的换行符.

At least as far as I can tell, the idea here is to ignore the existing line structure, and write out 8 words per line, regardless of line breaks in the input data. Assuming that's correct, I'd start by just reading words from the input, paying no attention to the existing line breaks.

从那里开始,就是将单词大写,将它们写出来,并且(如果您是 8 的倍数,则换行.

From there, it's a matter of capitalizing the words, writing them out, and (if you're at a multiple of 8, a new-line.

我还会在大部分工作中使用标准算法,而不是编写自己的循环来执行解析,例如读取和写入数据.由于模式基本上只是读取一个单词,修改它,然后写出结果,它非常适合 std::transform 算法.

I would also use standard algorithms for most of the work, instead of writing my own loops to do the pars such as reading and writing the data. Since the pattern is basically just reading a word, modifying it, then writing out the result, it fits nicely with the std::transform algorithm.

执行此操作的代码可能如下所示:

Code to do that could look something like this:

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

std::string to_upper(std::string in) {
    for (auto &ch : in)
        ch = toupper((unsigned char) ch);
    return in;
}

int main() {
    int count = 0;

    std::transform(
        std::istream_iterator<std::string>(std::cin),
        std::istream_iterator<std::string>(),
        std::ostream_iterator<std::string>(std::cout),
        [&](std::string const &in) {
            char sep = (++count % 8 == 0) ? '\n' : ' ';
            return to_upper(in) + sep;
        });
}

我们可以将每个字符串的大写实现为第二个 lambda,嵌套在第一个中,但 IMO 开始变得有点不可读.同样,我们可以使用 std::tranform 来实现 to_upper 内部的大写转换.

We could implement capitalizing each string as a second lambda, nested inside the first, but IMO, that starts to become a bit unreadable. Likewise, we could use std::tranform to implement the upper-case transformation inside of to_upper.