Re: [問題] String 取特定的字
※ 引述《blackall (犽★)》之銘言:
: 要讀取二進位數值後
: 要show出裡面共有幾個1
: 在判斷二進位數值後 若不是二進位數值要重新輸入
: 這邊都還ok
: 但是要算我的字串有幾個1的時候我就卡住了=^=
: 我想到是用IndexOf判斷有沒有1的這個數
: 之後就卡死@@" 判斷有沒有1之後我要怎麼樣count有幾個1
: EX:
: while(inputNumber.contains("1") && inputNumber.contains("0") )
: {
: while(inputNumber.indexOf("1") > 0)
: {
: count++;
: System.out.println("Your number include " + count + " 1. ");
: }
: }
檢查: inputNumber.matches("^[01]+$")
要 count 的話, 用 charAt loop 一次算是比較快的.
硬要寫短的話,
input.replace("0", "").length()
或 input.split("1").size -1 也可
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 202.155.236.82
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 5 篇):