亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用java substring函數提取出5個單詞?該怎么操作比較好?

如何使用java substring函數提取出5個單詞?該怎么操作比較好?

鳳凰求蠱 2021-10-11 14:10:11
有一個字符串 string str="I like apple and pear";我想用substring函數分別提取出這5個單詞,請問如何實現?請舉例說明,謝謝謝謝回復!如果字符串里的文字是隨機的要如何解決呢?
查看完整描述

2 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

可以將字符串按照空格分隔。。
string temp[]=str.split(" ");這個temp數組里面就是所有的單詞了。。也可以解決
文字隨機情況



查看完整回答
反對 回復 2021-10-16
?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

public class Test {    public static void main(String[] args) {        String str = "i like apple and pear";        String temp = str.substring(01);        String temp1 = str.substring(26);        String temp2 = str.substring(712);        String temp3 = str.substring(1316);        String temp4 = str.substring(1721);        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);        }    }}

 已測試,如下圖:

 


查看完整回答
反對 回復 2021-10-16
  • 2 回答
  • 0 關注
  • 255 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號