How do I parse a String to get the decimal and a word with a dot properly?

南楼画角 提交于 2019-12-11 10:25:56

问题


How do I differentiate the difference in finding a decimal but at the same time ignoring it if it is a period?

For example, assume Scanner

String s = "2015. 3.50 please";

When I use the function scanner.hasNextFloat(), how do I ignore Hi.?

I am only scanning 1 line. I need to identify whether a word is string, integer, or float. My final result should look something like this:

This is a String: 2015.
This is a float: 3.50
This is a String: please

But in my conditions when I use scanner.hasNextFloat(); it identifies 2015. as a float.


回答1:


In Java, you might use a regular expression. One or more digits, followed by a literal dot and then two digits. Something like

String s = "Hi. 3.50 please";
Pattern p = Pattern.compile(".*(\\d+\\.\\d{2}).*");
Matcher m = p.matcher(s);
Float amt = null;
if (m.matches()) {
    amt = Float.parseFloat(m.group(1));
}
System.out.printf("Ammount: %.2f%n", amt);

Output is

Ammount: 3.50



回答2:


You can use regular expression to match the numbers

    String[] str = { " Hi, My age is 12", "I have 30$", "Eclipse version 4.2" };
    Pattern pattern = Pattern.compile(".*\\s+([0-9.]+).*");
    for (String string : str) {
        Matcher m = pattern.matcher(string);
        System.out.println("Count " + m.groupCount());
        while (m.find()) {
            System.out.print(m.group(1) + " ");
        }
        System.out.println();
    }

Output:

Count 1 12 Count 1 30 Count 1 4.2

If numbers can in power of e or E, add [0-9.eE] in the pattern String




回答3:


I'm assuming you mean java, as javascript doesn't have a Scanner.

    String s = "Hi. 3.50 please";

    Scanner scanner = new Scanner(s);
    while (scanner.hasNext()){
        if (scanner.hasNextInt()){
            System.out.println("This is an int: " + scanner.next());
        } else if (scanner.hasNextFloat()){
            System.out.println("This is a float: " + scanner.next());
        } else {
            System.out.println("This is a String: " + scanner.next());
        }

    }

Output:

This is a String: Hi.
This is a float: 3.50
This is a String: please

So, what's the problem?



来源:https://stackoverflow.com/questions/33249160/how-do-i-parse-a-string-to-get-the-decimal-and-a-word-with-a-dot-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!