JAvaプログラミング--文字列、長さ、分割文字列を指定します.
1482 ワード
package com.henu;
import java.util.Arrays;
public class Demo01 {
public static void main(String[] args) {
String str = "abcdefg";
int chars = 2;
String[] res = split(str,chars);
System.out.println(Arrays.toString(res));
}
public static String[] split(String str,int chars){
int len = str.length();
String[] res = null;
if (len % 2 == 0){
res = new String[len/chars];
}else{
res = new String[len/chars+1];
}
String mid = "";
int k = 0;
for (int i = 0; i < str.length(); i+=chars) {
if (i + chars < str.length()){
mid = str.substring(i,i+chars);
}else{
mid = str.substring(i);
}
if (k < res.length) {
res[k++] = mid;
}
}
return res;
}
}
package com.henu;
import java.util.Arrays;
public class Demo02 {
public static void main(String[] args) {
String str = "abcdefg";
int chars = 3;
String[] res = split(str,chars);
System.out.println(Arrays.toString(res));
}
public static String[] split(String str,int chars){
int n = (str.length()+ chars - 1)/chars;
String ret[] = new String[n];
for(int i=0; i