华为机试题--字符串分隔

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

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

import java.util.Scanner;

public class Main {

	/**连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
	•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理
	 * @param args
	 */
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		while(sc.hasNext()){
			
			String word = sc.nextLine();
			
			if(word.length()<=8&&word.length()>0){//如果字符串长度介~8之间
				
				StringBuffer medium = new StringBuffer(word);//将字符串(不可变长word转变为StringBuffer(可变长度的字符串)
				
				medium.append("0000000");//在字符串后面补全7个零
				String result = medium.substring(0, 8);//截取[0,8)个元素
				System.out.println(result);
			}else if(word.length()==0){
				
				break;//长度是零的直接跳出循环(因此在上面medium.append("0000000");只需补全7个零
				
			}else{
				
				for(int i=0;i<12;i++){//100%8约等12
					
					StringBuffer medium = new StringBuffer(word);
					
					String result = medium.substring(8*i, 8*(i+1));//获取剩余部分的元
					
					System.out.println(result);
					
					result = medium.substring(8*(i+1));
					
					if(result.length()<=8&&result.length()>0){
						
						StringBuffer next = new StringBuffer(result);//word.append("0000000");
						
						next.append("0000000");
						
						result = next.substring(0, 8);
						
						System.out.println(result);
						
						break;
					}
				}
				
			}
			
		}
		
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值