【问题标题】:How to Get a Number From a String of Unknown Size (Java)如何从未知大小的字符串中获取数字(Java)
【发布时间】:2017-01-11 14:37:59
【问题描述】:

我正在制作一个程序的一部分,该程序将检查输入到 JTextArea 中的字符串是否是数字,如果是,字符串包含什么数字(顺便说一下,不是整个字符串都包含数字,我不不知道这个数字是多少位数)。我已经知道如何从 JTextArea 获取字符串以及如何检查字符串是否包含数字。但我不知道如何从字符串中获取确切的数字。以下是我正在使用的两种方法:

//no problems with this method, it's just here for reference.
public static boolean isNum(char[] c, int index){
   //I want to include numbers 0-9
   for(int i = 0; i < 10; i++){
      if(c[index].equals(i(char)) || c[index].equals('.')){
         return true;
      }
   }
   //if the character is not a number 0-9, it is not a number, thus returning false.
   return false;
}

和:

//I need a string parameter to make it easier to get the text from the JTextArea
public static float checkNum(String s){
    //a List to hold the digits
    List<Char> digits = new List<Char>();
    //a char array so I can loop through the string
    char[] c = s.toCharArray();

    for(int i = 0; i < c.length(); i++){
        //if the character is not a number, break the loop
        if(!isNum(c[i])){
            break;
        }
        else{
            //if the character is a number, add it to the next digit
            digits.add(c[i]);
        }
    }
//insert code here.
}

也许我应该将字符列表转换回字符数组,然后将其转换为字符串,然后将其转换为浮点数?如果是这样,我该怎么做?

编辑:谢谢大家,我研究了正则表达式,但我认为这不会完成这项工作。我正在寻找具有未知位数的 一个 号码。不过,我确实知道数字末尾会有一个空格(或至少是一个非数字值)。

【问题讨论】:

  • 你能澄清一下吗?使用BigIntegerBigDecimal 可能会解决您的问题,但要澄清一下,您从哪里提取价值?您提到您的整个字符串可能不是一个数字(这很好,因为您可以解析非数字),但只是看到您尝试使用的两种方法,而不是在 what context 他们'用起来有点难。
  • 我正在尝试在(各种类型的)等式中查找数字,因此我可以对这些数字进行运算(加、减等)。

标签: java list casting type-conversion


【解决方案1】:

您应该使用正则表达式。在 java 中,您可以像这样遍历数字的每个实例:

java.util.regex.Pattern;
java.util.regex.Matcher;

Pattern p = Pattern.compile("\\d+?\\.\\d+");
Matcher m = p.matcher(inputString);

while(m.find())
  //do some string stuff

或者,您可以通过将 while 循环替换为以下内容,在包含一组数字的字符串中查找一个匹配项:

String digits = m.group(1);
double number = Double.valueOf(digits);

有关其工作原理的更多信息,请查看正则表达式。这个网站特别有用https://regexone.com/

【讨论】:

  • 您的匹配示例不正确。 String.matches(String expr) 返回 boolean'
  • 另外,String.numericValueOf 不存在。
  • 谢谢,如果我修改它以适应我正在做的事情,这似乎会起作用。但我暂时不会知道,因为我现在还没有东西可以测试代码。
  • 我编辑了我的答案以考虑其他人的 cmets,因此当您有一台机器进行测试时会更容易。
  • 就字符串长度未知而言,您不能只将匹配的数字分配给 int。
【解决方案2】:

您可以使用正则表达式来测试和提取任意长度的数字。 这是一个简单的示例方法,可以做到这一点:

public Integer extractNumber(String fromString){
    Matcher matcher = Pattern.compile("\\D*(\\d+)\\D*").matcher(fromString);
    return (matcher.matches()) ? new Integer(matcher.group(1)) : null;
}

如果要处理数字内的小数,可以将方法改为:

public Double extractNumber(String fromString){
    Matcher matcher = Pattern.compile("\\D*(\\d+\\.?\\d+)\\D*").matcher(fromString);
    return (matcher.matches()) ? new Double(matcher.group(1)) : null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多