[英]Extracting signs/symbols from a string in Java
我有一個帶有符號的字符串,我只想獲取符號並將它們放在字符串數組中,這是我所做的:
String str = "155+40-5+6";
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]", " ");
// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.trim().split(" ");
但是signsArray的第二個元素是一個空格,[+,--,+]
感謝您的時間。
您可以通過兩種方法執行此操作。 用一個空格替換多個相鄰的數字:
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]+", " ");
或者在最后一步中,在多個空格上分割:
// then get an array that contains the signs without spaces
String[] signsArray = signString.trim().split(" +");
只需更換" "
到""
在你的代碼
String str = "155+40-5+6";
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]","");
// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.split("");
這應該為您工作。 干杯
運行代碼的圖像
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.