题源 👉 字符串分隔_牛客题霸_牛客网 (nowcoder.com)
题目描述:
思路:
方法一:
判断可以分为几个长度为8的串、剩下几个字符。
遍历字符串s,输出完整长度的之后再输出处理长度不足的。
方法二:
借助 substring 方法截取字符串,可以使代码更简洁。
具体实现:
方法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int len = s.length();
int t = len / 8; // 可以将s分为t个完整的长度为8的串
int m = len % 8; // 剩下m个字符长度不足8
// 将t个完整长度为8的串输出
for(int i = 0; i < t; i++) {
for (int j = 0; j < 8; j++)
System.out.print(s.charAt(i * 8 + j));
System.out.println();
}
// 输出剩下m个字符并补0
if(m != 0) {
for (int i = t * 8; i < len; i++)
System.out.print(s.charAt(i));
for (int i = m; i < 8; i++)
System.out.print('0');
}
}
}
方法二:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringBuilder sb = new StringBuilder(s);
while(sb.length() > 8){
System.out.println(sb.substring(0, 8));
sb.delete(0, 8);
}
while(sb.length() > 0 && sb.length() < 8) {
sb.append('0'); // 看到一个改进方法,直接加8个0,最后截取8位
}
System.out.println(sb.toString());
}
}
时间复杂度:
O(n)