簡體   English   中英

從Java中的字符串中提取符號/符號

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM