public class Test {
public static void main(String[] args) {
String str = "i like apple and pear";
String temp = str.substring(0, 1);
String temp1 = str.substring(2, 6);
String temp2 = str.substring(7, 12);
String temp3 = str.substring(13, 16);
String temp4 = str.substring(17, 21);
System.out.println(temp + "," + temp1 + "," + temp2 + "," + temp3 + ","
+ temp4);
}
}
如果文字是随机的,可以通过String 的split()方法,以空格为分隔符,将文字变成字符数组,再输出:
public class Test {
public static void main(String[] args) {
String str = "a b a df d a f da fa d ";
String[] arr = str.split(" "); //返回数组arr
for(String s:arr)
System.out.println(s);
}
}
如果一定要求要用substring()来实现,必须用indexOf()返回空格的位置,再用substring返回具体字符:
public class Test {
public static void main(String[] args) {
String str = "i like apple and pear";
find(str);
}
public static void find(String s) {
int i = s.indexOf(" ");
String temp;
if (i != -1) {
temp = s.substring(0, i);
System.out.println(temp);
if (s.length() > 0) {
String new_s = s.substring(i).trim();
find(new_s);
}
}else{
System.out.println(s);
}
}
}
已测试,如下图:
用 str.split("")多好,里面写 正则
楼主为什么要用substring来提取单词呢。。。。可以将字符串按照空格分隔。。
string temp[]=str.split(" ");这个temp数组里面就是所有的单词了。。也可以解决
文字随机情况