题解 | #字符串分隔#

字符串分隔

https://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7

先获取输入字符串的长度,根据长度判断是否是8的整数倍,如果不是则算出需要填充的位数,通过concat拼接上对应的位数构成新的8的整数倍的字符串。然后我们通过循环,只要不是最后一次循环,直接截取8位,否则是最后一次不需要写后面的截取长度。

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String content = in.nextLine();
        int length = content.length();
        if (length % 8 != 0) {
            int fillLength = (length / 8 + 1) * 8 - length;
            for (int i = 1; i <= fillLength; i ++) {
                content = content.concat("0");
            }
        }
        for (int i = 0; i <= length / 8; i ++) {
            if (i != length / 8) {
                System.out.println(content.substring(i * 8, i * 8 + 8));
            } else {
                System.out.println(content.substring(i * 8));
            }
        }
    }
}

华为OD题库 文章被收录于专栏

记录华为OD解答思路及过程

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务