字符串分隔

本文介绍了一种将连续输入的字符串按长度为8进行分段处理的方法,并通过示例演示了如何使用Java实现这一功能,包括如何处理非8整数倍长度的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组; 
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。 

输入描述:

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

输出描述:

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

示例1

输入

abc
123456789

输出

abc00000
12345678
90000000

解析:

首先利用Math的ceil()方法对字符串长度以8分割后的长度进行向上取整,然后利用String的substring()方法对字符串进行截取,每8个字符截取一次,当小于8个字符截取后,给它补上0即可。

实现代码:

import java.util.Scanner;
import static java.lang.Math.*;

public class Main{

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s1[] = new String[13];
		String s2[] = new String[13];
		int count = 0;
		String str1 = sc.nextLine();
		String str2 = sc.nextLine();
		double temp1 = (double)str1.length()/8;
		int length1 = (int)Math.ceil(temp1);
		double temp2 = (double)str2.length()/8;
		int length2 = (int)Math.ceil(temp2);
		while(length1>0){
			if(length1 == 1){
				s1[count] = str1.substring(8*count,str1.length());
				for(int i=0;i<8*(count+1)-str1.length();i++){
					s1[count] = s1[count] + "0";
				}
			}else{
				s1[count] = str1.substring(0+8*count, 8+8*count);
			}	
			System.out.println(s1[count]);
			count++;
			length1--;
		}
		count = 0;	
		while(length2>0){
			if(length2 == 1){
				s2[count] = str2.substring(8*count,str2.length());
				for(int i=0;i<8*(count+1)-str2.length();i++){
					s2[count] = s2[count] + "0";
				}
			}else{
				s2[count] = str2.substring(0+8*count, 8+8*count);
			}	
			System.out.println(s2[count]);
			count++;
			length2--;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值