有一個字符串 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
提交
取消

