欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【HJ4】字符串分隔

程序员文章站 2022-07-14 20:12:19
...

题目描述

连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

输入描述:
连续输入字符串(输入多次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组

示例1

输入
abc
123456789
输出
abc00000
12345678
90000000

题解思路

  1. 暴力求解:使用一个 8 字符长度的缓存数组,依次存放目标字符,满 8 个字符就输出;不满 8 个字符则判断是否需要末尾写入 0(即判断缓存数组中是否存入字符)
  2. 利用 C++ string 的 substr 分割函数

代码实现

#include <iostream>
#include <cstring>

int main()
{
    using namespace std;
    char str[101] = {0};
    char temp[9] = {0};
    while(cin.getline(str, 101)) {
        int len = strlen(str);
        int k = 0;
        for(int i = 0; i < len; ++i) {
            temp[k++] = str[i];
            if(k == 8) {
                cout << temp << endl;
                k = 0;
            }
        }
        if(k != 0) {
            while(k < 8) {
                temp[k++] = '0';
            }
            cout << temp << endl;
        }
    }
    return 0;
}

【HJ4】字符串分隔
使用 C++ string 的代码实现:

#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string str;
    while(cin >> str) {
        while(str.size() >= 8) {
            cout << str.substr(0, 8) << endl;
            str = str.substr(8);
        }
        if(str.size() > 0) {
            str += "00000000";
            cout << str.substr(0, 8) << endl;
        }
    }
    return 0;
}

【HJ4】字符串分隔