有一个字符串 string str="I like apple and pear";我想用substring函数分别提取出这5个单词,请问如何实现?请举例说明,谢谢谢谢回复!如果字符串里的文字是随机的要如何解决呢?
2 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
可以将字符串按照空格分隔。。
string temp[]=str.split(" ");这个temp数组里面就是所有的单词了。。也可以解决
文字随机情况
扬帆大鱼
TA贡献1799条经验 获得超9个赞
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); } }} |
已测试,如下图:
添加回答
举报
0/150
提交
取消

