//方法1
class ArrangedNumbers
{
public String[] splitSpace(String line )
{
line=line.trim();
int begin=0;
int end=line.indexOf(" ");
String[] numbers = new String[line.length()];
for (; end >= 0 && end < line.length(); begin++) {
numbers[i] = line.substring(begin, end);
System.out.println("numbers[" + i + "]=" + numbers[i++]);
begin = end;//把end的值赋值给begin
end++;//后面肯定至少有一个空格,去掉
while (end < line.length()) {//当小于整个长度时
end = line.indexOf(" " , end);//查看下一个空格的位置
if (end > 0 && line.substring(begin, end).equals(" ")) {//如果在begin和end之间存在空格,丢弃这个空格
begin = end;
end++;
} else {//如果不是空格或者已经到了字符串结尾,退出while循环
break;
}
}
}
numbers[i]=line.substring(begin);
return numbers;
}
}
//方法2
class ArrangedNumbers
{
public String[] splitSpace(String line )
{
line = line.trim();
int begin = 0, end = 0;
String[] numbers = new String[line.length()];
char cur;
int flag = 0;
boolean has = true;
for(int i = 0; i < line.length(); i++){
cur = line.charAt(i);
if(cur != ' '){
has = true;
end = i;
}else{
end ++;
if(has){
numbers[flag ++] = line.substring(begin, end);
begin = end;
has = false;
}
begin ++;
}
}
if(has){
numbers[flag++] = line.substring(begin);
}
return numbers;
}
}
感谢楼上的!
end = line.indexOf(" ", end)) == begin有点不明白阿