java截取字符串—substring的用法

前言:遇到如下问题,excel导出来的数据多了一个逗号,把结尾的逗号去掉。

在这里插入图片描述

 	    String area = "";
            String pNo = "";
            String room = "";

            TPositionExample pex = new TPositionExample();
            pex.createCriteria().andExhibitionIdEqualTo(exhibitionId).andGroupidEqualTo(o.getGroupId());
            List<TPosition> positionList = positionService.selectByExample(pex);

            if (CollectionUtils.isNotEmpty(positionList)) {
                for (TPosition position : positionList) {
                    pNo += position.getExhibitonPositionNo() + ",";

                    area += StringUtils.isEmpty(position.getArea()) ? "0," : (position.getArea() + ",");

                    room += position.getRoomName() + ",";

                }
                if (pNo != null && pNo.lastIndexOf(",") != -1) {
                    pNo = pNo.substring(0, pNo.length() - 1);
                }
                if (area != null && area.lastIndexOf(",") != -1) {
                    area = area.substring(0, area.length() - 1);
                }
                if (room != null && room.lastIndexOf(",") != -1) {
                    room = room.substring(0, room.length() - 1);
                }

            }

解决:只拿一个字段只举一个例子

String pNo = "";
for (TPosition position : positionList) {
                    pNo += position.getExhibitonPositionNo() + ",";
                }
if (pNo != null && pNo.lastIndexOf(",") != -1) {
                    pNo = pNo.substring(0, pNo.length() - 1);
                }

总结:不知道是否在这里看出了重点,重点就是substring,substring的用法:substring() 方法用于提取字符串中介于两个指定下标之间的字符。提示一点:substring() 不接受负的参数。刚开始我没有判空,直接报异常了,就是因为substring() 为负的原因。加上判空就好了。

1.substring(x)是从字符串的第x个字符截取
2.substring(x,y)是从字符串的第x个字符到第y个字符位置的停止
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页