Hj4: 字符串分隔
描述
•输入一个字符串,请按长度为8拆分每个输入字符串并进行输出;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(每个字符串长度小于等于100)
输出描述:
依次输出所有分割后的长度为8的新字符串
#include <string>
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin>>str)//不是一个主函数只输入一次字符串!
{
if(str.size()%8!=0) eg:6%8等于6 ,不等于0!
{
int count=8-(str.size()%8);//*****第一个8不能改成str.size();
str.append(count,'0');//尾部一次添加多个数据
}
for(int i=0;i<str.size();i+=8)
{
string s1=str.substr(i,8);
cout<<s1<<endl;
}
}
return 0;
}
Getline()函数的使用!
getline(basic_istream<_CharT, _Traits> &&__is, basic_string<_CharT, _Traits, _Alloc> &__str)
重点:遇到空格不结束
例题:华为试题
描述
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
数据范围:输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000
输入描述:
输入一行字符串,可以有空格
输出描述:
统计其中英文字符,空格字符,数字字符,其他字符的个数
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string str;
int count_alpha=0,count_digit=0,count_space=0,count_other=0;
while( getline(cin, str))
{
for(int i=0;i<str.size();i++)
{
if(isalpha(str[i]))
{
count_alpha++;
}
else if(isdigit(str[i]))
{
count_digit++;
}
else if(isspace(str[i]))
{
count_space++;
}
else{
count_other++;
}
}
cout<<count_alpha<<endl;
cout<<count_space<<endl;
cout<<count_digit<<endl;
cout<<count_other<<endl;
}
return 0;
}