【问题标题】:Best way to convert this String to int将此字符串转换为 int 的最佳方法
【发布时间】:2015-10-29 02:57:16
【问题描述】:
好的,我有 3 个这样的字符串
String c = "coins<col=ffffff> x <col=ffff00>";
String c2 = "coins<col=ffffff> x <col=ffffff>100k (100,000)";
String c3 = "coins<col=ffffff> x <col=00ff80>10m (10,000,000)";
对于我使用的字符串“c”:
Integer.parseInt(i.getMessage().toLowerCase().replace(c, "").replace(",", ""));
问题在于 String c2 和 c3 不同。
我正在努力解决这个问题
int c2 = 100000;
int c3 = 10000000;
请帮忙!
【问题讨论】:
标签:
java
string
parsing
integer
int
【解决方案1】:
没有正则表达式也一样简单。
public class Stripper
{
public static void main (String[] args)
{
String c = "coins<col=ffffff> x <col=ffff00>";
String c2 = "coins<col=ffffff> x <col=ffffff>100k (100,000)";
String c3 = "coins<col=ffffff> x <col=00ff80>10m (10,000,000)";
String stripped = strip (c);
if (!stripped.isEmpty ())
System.out.println (Integer.parseInt (stripped));
String stripped2 = strip (c2);
if (!stripped2.isEmpty ())
System.out.println (Integer.parseInt (stripped2));
String stripped3 = strip (c3);
if (!stripped3.isEmpty ())
System.out.println (Integer.parseInt (stripped3));
}
private static String strip (String text)
{
int first = text.indexOf ('(');
if (first < 0)
return "";
int last = text.indexOf (')', first);
if (last < 0)
return "";
return text.substring (first + 1, last).replaceAll (",", "");
}
}