[英]How to remove all character from a string until a range of accepted characters?
例如,我有一個字符串"0.01"
。 我怎樣才能得到"1"
?
我試過
String a = "0.01"
a = a.replaceAll(".", "");
a = a.replaceAll("0", "");
但這不起作用,因為字符串可以是"0.0105"
,在這種情況下,我想保留"105"
我也試過
String a = "0.01"
b = a.substring(s.indexOf("0")+3);
這也不起作用,因為字符串可以是"0.1"
,我想保留"1"
簡而言之,我想刪除所有0
或.
直到它以非 0 開頭。 該字符串實際上是從 Double 轉換而來的。 我不能簡單地將*100
與 Double 一起使用,因為它可以是0.1
String a = "0.01";
String[] b = a.split("\\.");
a = b[0]+b[1];
int c = Integer.parseInt(a);
你將得到 1 作為 integer。當你想添加一些東西時,你可以添加然后返回到字符串,如:
c = c+3;
String newa = String.valueOf(c);
System.out.println(newa);
使用正則表達式[1-9][0-9]*
表示第一個數字為1-9
,然后后續數字( 可選)為0-9
。 從課程:正則表達式了解更多關於正則表達式的信息。
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:
105
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.