2017-09-04 21 views
0

字符串我有迹象字符串,我想只得到标志,并把它们在一个字符串数组,这里是我做了什么:提取标志/符号从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(" "); 

然而signArray的第二个元素是一个空格,[+, - - ,+]

谢谢你的时间。

+0

https://stackoverflow.com/questions/17516049/java-removing-numeric-values-from-string – soorapadman

回答

2

你可以通过几种方法做到这一点。无论是用一个空格代替多个相邻数字:

// 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(" +"); 
+0

这就行了,谢谢! –

1

只需更换" """在你的代码

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(""); 

这应该适合你。干杯

的运行代码图像 enter image description here

+0

它不会,但使用:str.replaceAll(“[^ + - ] +”,“”);或str.replaceAll(“[0-9] +”,“”);没有,谢谢你的帮助:) –

+0

它为我工作,我有附加图像也......通常你的问题解决了 – iamdeowanshi