java判斷字串是否可以轉為數字

來源:互聯網
上載者:User

java運算中,常涉及將String 型的字串轉為int 型數位情況。

哪些字串可以轉為數字,哪些不可以呢,不能總以Integer.parseInt() 是否拋出異常來判斷。

剛好碰到了轉換情況,就總結了下,分享出來。


定義方法簽名

/*** 查看一個字串是否可以轉換為數字* @param str 字串* @return true 可以; false 不可以*/public static boolean isStr2Num(String str) { }

方法體該如何?呢。兩種方式


方法1  Integer.parseInt 轉換

try {Integer.parseInt(str);return true;} catch (NumberFormatException e) {return false;}

方法2  Regex

Pattern pattern = Pattern.compile("^[0-9]*$");Matcher matcher = pattern.matcher(str);return matcher.matches();


Integer 還有一個靜態方法valueOf(String s),查看源碼

public static Integer valueOf(String s) throws NumberFormatException {    return Integer.valueOf(parseInt(s, 10));}

valueOf(String s) 也還是先通過parseInt() 先將字串轉換為數字,然後再轉換為Integer對象的

而 parseInt(String s) 返回的是int 型變數,節省了堆記憶體的開銷

public static int parseInt(String s) throws NumberFormatException {    return parseInt(s,10);}

所以,這裡的判斷使用parseInt 就可以了。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.