前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >华为oj之字符串分割

华为oj之字符串分割

作者头像
Enjoy233
发布2019-03-05 14:55:34
6080
发布2019-03-05 14:55:34
举报

题目: 字符串分隔

  • 热度指数:6139 时间限制:1秒 空间限制:32768K
  • 本题知识点: 字符串

题目描述

•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;

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

输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组
输入例子:
abc
123456789
输出例子:
abc00000
12345678
90000000

在线提交网址: http://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7?tpId=37&tqId=21227&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking

分析:

根据字符串长度, 分length>8, <8, =8 三种情况即可, 另外还有一种递归的方法可以解决.

已AC代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
    string str;
    while(getline(cin, str))
    {
        if(str.empty()) return 0;
        if(str.length() == 8) cout<<str<<endl;
        else if(str.length() < 8 && str.length()>0)
        {
            cout<<str;
            for(int i = 0; i <= 8-str.length()-1; i++) cout<<'0';
            cout<<endl;
        }
        else if(str.length() > 8)
        {  
            int lastlen=str.length() % 8;
            int frontlen = str.length()-lastlen;
            for(int i = 0; i <= frontlen - 1; i++)
            {
                if(i==0 || i%8 != 7) cout<<str[i];
                if(i%8 == 7)
                {
                    cout<<str[i]<<endl;
                    continue;
                }
            }                 
            for(int j = 0; j <= lastlen-1; j++) cout<<str[frontlen+j];
            if(lastlen>0)
            {
                for(int i = 0; i <= 8-lastlen-1; i++)
                    cout<<'0';
                cout<<endl;                
            }
        }         
    }     
    return 0;
}

递归解法:

#include <iostream>
#include <string>
using namespace std;
void process(string str) {
    if (str == "")
        return;
    if (str.size() <= 8) {
        str.append(8 - str.size(), '0');
        cout << str << endl;
        return;
    }
    cout << str.substr(0, 8) << endl;
    process(str.substr(8, str.size()));
}
int main() {
    string str1, str2;
    cin >> str1 >> str2;
    process(str1);
    process(str2);
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年09月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目: 字符串分隔
  • 题目描述
    • 分析:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档