StrUtil.java 1.28 KB
package com.example.mina.util;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 杜云山
 * @date 2021/03/05
 */
@Slf4j
public class StrUtil {

    public static int[] parseCommaInts(String str) {
        if (str == null) {
            return new int[0];
        }

        String[] ss = str.split(",");
        int[] ids = new int[ss.length];

        int count = 0;
        for (int i = 0; i < ss.length; i++) {
            int p = toInt(ss[i]);
            ids[i] = p;
            if (p >= 0) {
                count++;
            }
        }

        if (count < ss.length) {
            int[] ids2 = new int[count];
            count = 0;
            for (int i = 0; i < ss.length; i++) {
                if (ids[i] >= 0) {
                    ids2[count++] = ids[i];
                }
            }

            ids = ids2;
        }

        return ids;
    }

    public static int toInt(String str) {
        if (isEmpty(str)) {
            return -1;
        }

        try {
            float f = Float.parseFloat(str.trim());
            return (int) f;
        } catch (Exception e) {
            log.error("{}, 无法转换为数字", str, e);
            return -1;
        }

    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

}