题目描述
•连续输入字符串,请按长度为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;