題目描述
•連續輸入字符串,請按長度爲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;