数据类型扣除

时间:2015-12-30 12:10:15

标签: java type-conversion

我有一个从CSV / Excel /文本文件中读取的值列表,并希望在java中查找日期/数字/浮点数或字符串的数据类型。 找到那些类型的有效方法是什么?

Eg.,["America","Thailand","Srilanka"] - String
[123,456,789] - Number
[12-11-1990,null,13-09-1989] - Date.
[$300,$450,$500,₹450,€340] - Currency(type of number)

1 个答案:

答案 0 :(得分:1)

根据提供的少量信息,您可以从此代码段开始。根据您的需求/数据修改检测标准。

/**
 * Any value which contains at least one `Letter` is classified
 * as String.
 */
static boolean isString(String value) {
    for (int i = 0; i < value.length(); i++) {
        if (Character.isLetter(value.charAt(i))) {
            return true;
        }
    }
    return false;
}

/**
 * Any value which contains only `Digits` is classified as
 * Number.
 */
static boolean isNumber(String value) {
    for (int i = 0; i < value.length(); i++) {
        if (!Character.isDigit(value.charAt(i))) {
            return false;
        }
    }
    return true;
}

/**
 * Any value which matches the `Date` pattern is classified as
 * Date.
 */
static boolean isDate(String value) {
    // pattern needs some finetuning not matching invalid dates
    // e.g. 77-88-9999
    return value.matches("[0-9]{2}-[0-9]{2}-[0-9]{4}");
}

public static void main(String[] args) {
    String[] values = {
        "America", "Thailand", "Srilanka",
        "123", "456", "789",
        "12-11-1990", "null", "13-09-1989",
        "12.11"
    };
    for (String value : values) {
        String type;
        if ("null".equals(value)) {
            type = "null";
        } else if (isString(value)) {
            type = "string";
        } else if (isNumber(value)) {
            type = "number";
        } else if (isDate(value)) {
            type = "date";
        } else {
            type = "unknown";
        }
        System.out.printf("%-7s: %s%n", type, value);
    }
}

<强>输出

string : America
string : Thailand
string : Srilanka
number : 123
number : 456
number : 789
date   : 12-11-1990
null   : null
date   : 13-09-1989
unknown: 12.11