[英]How to remove all character from a string until a range of accepted characters?
For example, I have a string "0.01"
.例如,我有一个字符串
"0.01"
。 How can I get "1"
?我怎样才能得到
"1"
?
I had tried我试过
String a = "0.01"
a = a.replaceAll(".", "");
a = a.replaceAll("0", "");
but this won't work as the string can be "0.0105"
and in this case, I want to keep "105"
但这不起作用,因为字符串可以是
"0.0105"
,在这种情况下,我想保留"105"
I also tried我也试过
String a = "0.01"
b = a.substring(s.indexOf("0")+3);
this also won't work as the string can be "0.1"
which I want to keep "1"
这也不起作用,因为字符串可以是
"0.1"
,我想保留"1"
In short, I want to remove all 0
or .
简而言之,我想删除所有
0
或.
until it starts with non-0.直到它以非 0 开头。 The string is actually converted from Double.
该字符串实际上是从 Double 转换而来的。 I can't simply
*100
with the Double as it can be 0.1
我不能简单地将
*100
与 Double 一起使用,因为它可以是0.1
String a = "0.01";
String[] b = a.split("\\.");
a = b[0]+b[1];
int c = Integer.parseInt(a);
You will get 1 as integer. When you want to add something you can add and then return to string like:你将得到 1 作为 integer。当你想添加一些东西时,你可以添加然后返回到字符串,如:
c = c+3;
String newa = String.valueOf(c);
System.out.println(newa);
Use the regex, [1-9][0-9]*
which means the first digit as 1-9
and then subsequent digits ( optional ) as 0-9
.使用正则表达式
[1-9][0-9]*
表示第一个数字为1-9
,然后后续数字( 可选)为0-9
。 Learn more about regex from Lesson: Regular Expressions .从课程:正则表达式了解更多关于正则表达式的信息。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "0.0105";
Pattern pattern = Pattern.compile("[1-9][0-9]*");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
str = matcher.group();
}
System.out.println(str);
}
}
Output: Output:
105
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.