public class Test1 { public static void main(String[] args){ String a = "abcd"; String[] strs = new String[a.length()-1]; for(int i=0;i<a.length()-1;i++){ strs[i] = a.substring(i, i+2); System.out.println(strs[i]); } } }
String str = "abcdefg"; ArrayList list = new ArrayList(); int i = 0; for (i = 0; i < str.length() - 1; i += 2) { list.add(str.substring(i, i + 2)); } list.add(str.substring(i)); for (i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
public class Test1 {
public static void main(String[] args){
String a = "abcd";
String[] strs = new String[a.length()-1];
for(int i=0;i<a.length()-1;i++){
strs[i] = a.substring(i, i+2);
System.out.println(strs[i]);
}
}
}
ArrayList list = new ArrayList();
int i = 0;
for (i = 0; i < str.length() - 1; i += 2) {
list.add(str.substring(i, i + 2));
}
list.add(str.substring(i));
for (i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
这个会报错的。
for(int i=0;i<a.length()-1;i++){
strs[i] = a.substring(i, i+2);
System.out.println(strs[i]);
}
在这里面要在写个if(i+2>a.length()){
strs[i] = a.substring(i, a.length());
break;
}
所以没问题的
//3L,你打开String类的substring方法
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
//我的substring语句:strs[i] = a.substring(i, a.length());
//我的endIndex是a.length(),而count也是a.length()
//所以不会报错
//事实上我的业务也没有越界的操作,endIndex其实程序不会尝试去读,所以不会报错
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
public class Test1 {
public static void main(String[] args){
String a = "abcd";
String[] strs = new String[a.length()-1];
for(int i=0;i<a.length()-1;i++){
if(i<a.length()-2){
strs[i] = a.substring(i, i+2);
}else{
strs[i] = a.substring(i);
}
System.out.println(strs[i]);
}
}
}
public static void main(String[] args){
String a = "abcd";
String[] strs = new String[a.length()-1];
for(int i=0;i<a.length()-1;i++){
strs[i] = a.substring(i, i+2);
System.out.println(strs[i]);
}
}
}
public static void main(String[] args){
String s = "abcd";
char[][] result = splitString(s);
for(int i=0; i<result.length; ++i)
{
System.out.print(result[i][0]);
System.out.println(result[i][1]);
}
}
public static char[][] splitString(String s) {
char[][] charArray = null;
if(s!=null && s.length()>1)
{
charArray = new char[s.length()-1][2];
for(int i=0; i<s.length()-1; ++i)
{
charArray[i][0]=s.charAt(i);
charArray[i][1]=s.charAt(i+1);
}
}
return charArray;
}
StringBuffer buffer=new StringBuffer();
int strLength=strTemp.length()-1;//循环的总次数
int i=0;
while (i<strLength) {
if(i!=strLength-1) buffer.append(strTemp.substring(i,i+2)+",");
else buffer.append(strTemp.substring(i,i+2));
i++;
}
System.out.println(buffer);