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

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

如何將字符串值拆分為多個值

如何將字符串值拆分為多個值

函數式編程 2021-11-11 16:23:11
我有一個String從 svo 中獲得的值,即String reply=svo.getReplies();我得到的輸出就像--> "1:true,2:false,3:true,4:false,5:false,6:false"現在我想要的是將回復的存儲分開,并將所有回復存儲在每個回復的新變量中。例如:String firstVal= "true";String secondeVal= "false";// ... and so on. 我該怎么做?
查看完整描述

3 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

你可以用Map這個字符串制作。然后根據需要使用該地圖。

例如:String firstVal = map.get(1);


String s1 = "1:true,2:false,3:true,4:false,5:false,6:false";


Map<Integer, String> map = new HashMap<>();

for (String s : s1.split(",")){

        map.put(Integer.parseInt(s.substring(0, s.indexOf(":"))), s.substring(s.indexOf(":")+1));

    }


for (Integer key : map.keySet()) System.out.println(key + " " + map.get(key));


查看完整回答
反對 回復 2021-11-11
?
LEATH

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

您可以使用正則表達式來實現:


//Compile the regular expression patern

Pattern p = Pattern.compile("([0-9]+):(true|false)+?") ; 

//match the patern over your input

Matcher m = p.matcher("1:true,2:false,3:true,4:false,5:false,6:false") ; 


// iterate over results (for exemple add them to a map)

Map<Integer, Boolean> map = new HashMap<>();

while (m.find()) {

    // here m.group(1) contains the digit, and m.group(2) contains the value ("true" or "false")

    map.put(Integer.parseInt(m.group(1)), Boolean.parseBoolean(m.group(2)));

    System.out.println(m.group(2)) ;

}

更多關于正則表達式語法的信息可以在這里找到:https : //docs.oracle.com/javase/tutorial/essential/regex/index.html



查看完整回答
反對 回復 2021-11-11
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

您可以使用Pattern,并Stream在匹配結果應用到Stringreturrned通過svo.getReplies():


String input = "1:true,2:false,3:true,4:false,5:false,6:false";

String[] result = Pattern.compile("(true|false)")

  .matcher(input)

  .results()

  .map(MatchResult::group)

  .toArray(String[]::new);

 System.out.println(Arrays.toString(result)); // [true, false, true, false, false, false]

 String firstVal = result[0]; // true

 String secondVal = result[1]; // false

 // ...


查看完整回答
反對 回復 2021-11-11
  • 3 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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