[编程题]字符串分隔

题目描述

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

输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)

输出描述:
输出到长度为8的新字符串数组

输入例子:
abc
123456789

输出例子:
abc00000
12345678
90000000

思路解答:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> strarr;
string str;

while(getline(cin,str))
{
    int len =str.size();
    int num=len%8;
    if(num!=0)
    {
        str.insert(str.end(),8-num,'0');
    }
    int count=str.size()/8;
    for(int i=0;i<count;i++)
    {
        string str_tmp=str.substr(8*i,8);
        strarr.push_back(str_tmp);
    }
}
for(int i=0;i<strarr.size();i++)
{
    cout<<strarr[i]<<endl;
}
    return 0;
}

注意:
1.substr的用法

string substr (size_t pos = 0, size_t len = npos) const;//从指定位置返回指定长度的子字符串

例题

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

2.insert的用法

string (1)  
 string& insert (size_t pos, const string& str);
substring (2)   
 string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
c-string (3)    
 string& insert (size_t pos, const char* s);
buffer (4)  
 string& insert (size_t pos, const char* s, size_t n);
fill (5)    
 string& insert (size_t pos, size_t n, char c);
    void insert (iterator p, size_t n, char c);
single character (6)    
iterator insert (iterator p, char c);
range (7)   
template <class InputIterator>
   void insert (iterator p, InputIterator first, InputIterator last);

3.错误的地方

int count=str.size()/8;一开始写的是int count=len/8;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值