英文:
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
或.
,直到它以非零数开头。该字符串实际上是从Double转换而来的。我不能简单地对Double执行*100
,因为它可以是0.1
。
英文:
For example, I have a string "0.01"
. How can I get "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"
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"
In short, I want to remove all 0
or .
until it starts with non-0. The string is actually converted from Double. I can't simply *100
with the Double as it can be 0.1
答案1
得分: 2
String a = "0.01";
String[] b = a.split("\\.");
a = b[0] + b[1];
int c = Integer.parseInt(a);
// You will get 1 as an integer. When you want to add something you can add and then return it to a string like:
c = c + 3;
String newa = String.valueOf(c);
System.out.println(newa);
英文:
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:
c = c+3;
String newa = String.valueOf(c);
System.out.println(newa);
答案2
得分: 2
只需执行:
System.out.println(Integer.valueOf(testCase.replace(".", "")));
原文出自YCF_L。
英文:
Just do:
System.out.println(Integer.valueOf(testCase.replace(".", "")));
Credit to YCF_L
答案3
得分: 0
使用正则表达式 [1-9][0-9]*
,它表示第一个数字为 1-9
,然后后续的数字(可选的)为 0-9
。从 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);
}
}
输出:
105
英文:
Use the regex, [1-9][0-9]*
which means the first digit as 1-9
and then subsequent digits (optional) as 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:
105
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论