繁体   English   中英

将此字符串转换为 int 的最佳方法

[英]Best way to convert this String to int

好的,我有 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(",", ""));

事情是对于字符串 c2 和 c3 来说是不同的。

我试图得到这个

int c2 = 100000;

int c3 = 10000000;

请帮忙!

没有正则表达式也一样容易。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM