题解 | #字符串分隔#

字符串分隔

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        int lastStrLength = s.length() % 8;
        int len = s.length() - lastStrLength;


        if (len >= 8) {
            for (int i = 0; i < len; i = i + 8) {
                String substring = s.substring(i, i + 8);
                System.out.println(substring);
            }
        }

        if (lastStrLength > 0) {
            StringBuilder substring = new StringBuilder(s.substring(len, s.length()));
            while (substring.length() < 8) {
                substring.append(0);
            }
            System.out.println(substring);
        }

    }
}

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 读取输入字符串
        String input = scanner.nextLine();
        processString(input);

        scanner.close();
    }

    public static void processString(String input) {
        if (input == null || input.isEmpty()) {
            return;
        }

        StringBuilder s = new StringBuilder(input);

        // 如果字符串长度不是8的倍数,补0
        while (s.length() % 8 != 0) {
            s.append('0');
        }

        // 按8个字符一组输出
        for (int i = 0; i < s.length(); i += 8) {
            System.out.println(s.substring(i, i + 8));
        }
    }
}

全部评论

相关推荐

愤怒的潜伏者在开会:你不攻击他,我可攻击你了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务