字符串分隔

1、题目描述

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

长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

输入描述:

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

输出描述:

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

输入例子:

abc
123456789

输出例子:

abc00000
12345678
90000000

2、程序

方案一

基本思路:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    while(cin>>s){
        int count = 0;
        int i=0;
        while(i<s.length()){
            if(count<8){
            //一开始执行这一句,因为我们的初值设置为count=0
                cout<<s[i];
                i++;
                count++;
                //直到输出8个数字为止
            }
            else
            {
                cout<<endl;
                count = 0;
                //如果满8位则换行,然后重新置count为0,再执行上面的输出
            }
        }
        while(count<8){
            cout<<0;
            count++;
        }
        //最后一排的输出控制,如果不满8位补零输出
        cout<<endl;
    }
}

  

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

void print(const char *p);
char str[9]={0};
 
int main(){   
    string str1,str2;
    const char *p1,*p2;
    
    getline(cin,str1);
    getline(cin,str2);
    p1 = str1.c_str();
    p2 = str2.c_str();
    /*
    const char *c_str();
    c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 
    这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
    注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
    */
    print(p1);
    print(p2);
  
    return 0;
}
void print(const char *p){
    while(*p !=''){
   	//循环到字符串结束 
    int k=0;
    while((k++) < 8){
    //控制输出8位     
        str[k] = *p;
        if(*p == ''){
            str[k] = '0';
            continue;
        }
        p++;
    }   
    str[k] = '';
    for(int i=0;i<8;i++)
       cout << str[i];
    cout<<endl;   
    }
}

  

方案二

基本思路:调用库函数substr()截取字符串。

#include <stdio.h>
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string s1;
    string s2 = "0000000";
    unsigned int i = 0;
    while ( getline(cin, s1) )
    {          
        for (i = 0; i+8 < s1.length(); i=i+8)
        {              
            cout << s1.substr(i, 8) << endl;
        }
 
        if (s1.length() - i > 0)
        {
            cout << s1.substr(i, s1.length() - i) +  s2.substr(0, 8-(s1.length() - i))<< endl;
        }      
    }  
    return 0;
}
//getline遇到换行符,结束输入,进入while循环,利用string的substr函数取出字符串。

 

#include<iostream>
#include<string>
using namespace std;
void output(string str);
int main(){
    string str1; string str2;
    cin>>str1>>str2;
    output(str1);
    output(str2);    
    return 0;
}
void output(string str){
    int cir=str.size()/8;
    int last=str.size()%8;
    string fil="00000000";
    for(int i=0;i<cir;i=i+1)
        cout<<str.substr(i*8,8)<<endl;
    if(last>0) cout<<str.substr(8*cir)<<fil.substr(last)<<endl;
}

  

 

原文地址:https://www.cnblogs.com/yedushusheng/p/5519142.html