在字符串中查找所有的小数

遇到一个需求,显示字符串的时候需要给其中数据部分设置不同的颜色,于是简单撸了一个算法。
 public List<StringSegment> analyseContent(String content) {
        int c = 0;
        int n = 0;
        boolean isDigit = false;
        List<StringSegment> list = new ArrayList<>();
        for (int i = 0; i < content.length(); i++) {
            if (Character.isDigit(content.charAt(i)) || '.' == content.charAt(i)) {
                n++;
            } else {
                c++;
            }
            if (n == 1 && c == 0) {
                isDigit = true;
            }

            if (n == 0 && c == 1) {
                isDigit = false;
            }

            // 全是数字
            if (n == content.length()) {
                list.add(new StringSegment(1, 0, content.length()));
            } else if (c == content.length()) {
                // 全是汉字
                list.add(new StringSegment(0, 0, content.length()));
            } else {
                // 数字到了尽头
                if (isDigit) {
                    if (i == content.length() - 1) {
                        list.add(new StringSegment(1, content.length() - n, content.length()));
                    } else if (c == 1) {
                        list.add(new StringSegment(1, i - n, i));
                        i--;
                        c = 0;
                        n = 0;
                    }
                }

                // 汉字到了尽头
                if (!isDigit) {
                    if (i == content.length() - 1) {
                        list.add(new StringSegment(0, content.length() - c, content.length()));
                    } else if (n == 1) {
                        list.add(new StringSegment(0, i - c, i));
                        i--;
                        c = 0;
                        n = 0;
                    }
                }
            }
        }
        return list;
    }
public class StringSegment {
    // 0 字符串 1 实数
    public int type;
    public int from;
    public int end;

    public StringSegment(int type, int from, int end) {
        this.type = type;
        this.from = from;
        this.end = end;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值