HJ4 题解 | #字符串分隔#
字符串分隔
http://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7
思路:逐组处理,将一组字符串转化为char[]数组,8个字符一组放到新的char[]数组中,再将这个新的char[]数组转化为字符串输出。最后判断是否有剩余不够8个字符的一组,如果有,则补0,没有则不处理。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.next();
char[] c = str.toCharArray();
int len = str.length();
int n = len / 8;
for(int i = 0; i < n; i++){ //先处理个数够8的字符串
char[] c2 = new char[8];
for(int j = 0; j < 8; j++){
c2[j] = c[8*i+j];
}
String s2 = String.valueOf(c2);
System.out.println(s2);
}
if(len % 8 != 0){ //最后一组个数不够8的字符串补0
int m = len % 8;
char[] c3 = new char[8];
for(int i = 0; i < m; i++){
c3[i] = c[8*n+i];
}
for(int i = m; i < 8; i++){
c3[i] = '0';
}
String s3 = String.valueOf(c3);
System.out.println(s3);
}
}
}
}
- String转char[]数组:char[] c = str.toCharArray();
- char[]数组转String:String str = String.valueOf(c);