题解 | #字符串分隔#

字符串分隔

https://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <vector>

class HJ04 {
public:
    std::vector<std::string> chunk(std::string s, size_t sz, char pad = '0') {
        std::string buf(sz, '\0');
        std::vector<std::string> ans;
        int j = 0;

        for (int i = 0; i < s.size();) {
            if (j < sz) {
                buf[j++] = s[i++];
            }
            else {
                ans.push_back(buf);
                j = 0;
                // reset buffer
                for (int k = 0; k < sz; k++) {
                    buf[k] = '\0';
                }
            }
        }
        while (j < sz) {
            buf[j++] = pad;
        }
        if (!buf.empty()) {
            ans.push_back(buf);
        }
        
        return ans;
    }
};


int mystrcpy(char* s, const char* cs) {
    const char* p = cs;
    while (*p) {
        *s++ = *p++;
    }
    *s = '\0';
    return p - cs;
}


int main()
{
    char s[BUFSIZ] = { '\0' };
    HJ04 q;

    std::cin.get(s, BUFSIZ).get();
    // mystrcpy(s, "abcdefghijklmnopqrstuvwxyz");
    // std::cout << s << std::endl;

    std::vector<std::string> parts = q.chunk(std::string(s), 8);
    for (std::vector< std::string >::const_iterator it = parts.begin();
        it != parts.end(); ++it) {
        std::cout << *it << "\n";
    }

}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件

#华为笔试#
全部评论

相关推荐

喵_coding:项目太烂了外卖+点评啊 而且寒假实习差不多到时候了 hc没多少了 要实在想要找那只能投投大厂试试了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务