日期:2014-05-20  浏览次数:20706 次

Java代码 ,有点困惑不解

public class ar {
public static void main(String [] args)
{
String text ="To be or not to be";
int count = 0;
char separator = ' ';
int index = 0;
do
{
++count;
++index; //这里++index会导致index变成1 ,下面index  = text.indexOf(separator, index);为什么要从1开始?字符串String text ="To be or not to be";不应该是从0开始算的吗??0应该对应字符串T,1对应o,难道是从o开始索引的?
index  = text.indexOf(separator, index);
}while(index != -1);

String [] subStr = new String[count];
index = 0;
int endIndex = 0;

for(int i=0;i<count;++i)
{
endIndex = text.indexOf(separator,index);

if(endIndex == -1)
{
subStr[i] = text.substring(index);
}
else
{
subStr[i] = text.substring(index, endIndex);
}

index = endIndex +1;

}
for(String s:subStr)
{
System.out.println(s);
}
}

}


------解决方案--------------------
因为你的第一个空格出现在第三个位置,所以从第二个位置开始也没关系
------解决方案--------------------
这里主要是为了需要index在每次循环以后要加一
------解决方案--------------------
引用:
Java code?1234567891011121314151617181920212223242526272829303132333435363738394041public class ar {    public static void main(String [] args)    {        String text ="To be or not to b……

String text ="To be or not to be";
        int count = 0;
        char separator = ' ';
        int index = 0;
        ++count;
        ++index;
        System.out.println(index);//这里index=1
        //下面从T开始技术,T的位置为0,o的位置为1,空格的位置为2,返回2,所以Index=2
        index  = text.indexOf(separator, index);
        System.out.println(index);//这里输出2

------解决方案--------------------
楼主,楼主上面的那个++index起到的主要作用是自增以退出循环,改成index++也是一样的。如下:

do{
++count;
index++; //改成这样也是一样的,主要的作用是让index自增,退出循环
index  = text.indexOf(separator, index); //其实index输出的是空格所在的索引的位置
System.out.println("index = " + index);
}while(index != -1);
//上面的循环主要是获得count的值
String [] subStr = new String[count];


解析这个字符串何必要做两次呢循环呢,其实很简单的,几行代码就可以了:


public class ar {
public static void main(String [] args){
String text ="To be or not to be";
String[] textArr = text.split(" ");