将此String转换为int的最佳方法

时间:2015-10-29 02:57:17

标签: java string parsing integer int

好的,我有3个看起来像这样的字符串

C:\Program Files(x86)\Java\jdk1.8.0_31\bin

For String" c"我用过:

C:\Program Files\Java\jdk1.8.0_31\bin

对于String c2和c3来说它是不同的。

我试图搞定这个

int c2 = 100000;

int c3 = 10000000;

请帮忙!

1 个答案:

答案 0 :(得分: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 (",", "");
  }
}
相关问题