您的位置:首页 > 编程语言 > Java开发

Java中字符串中存在空格引发的问题,及解决方法。

2014-07-17 21:29 651 查看
我需要将字符串“1000, 1001, 1002”中的数字存入数据库中类型为int的字段中。

首先:将字符串转换为字符串数组:

 假设: cts = "1000, 1001, 1002";
String[] st = cts.trim().split(",");
for(int i = 0; i < st.length; i++){
Culture_lace cl = new Culture_lace();
cl.setLid(lace.getId());
cl.setCtid(Integer.parseInt(st[i]));  // 在这里出现java.lang.NumberFormatException: For input string: " 1001"
cl.setStatus("1");
session.save(cl);
}


然后上网查了才知道: .trim()方法只能去掉字符串首尾的空格,中间的空格去不掉。
所以解决方法是:

  给每个数组元素添加 .trim()方法,即: 

改为 cl.setCtid(Integer.parseInt(st[i].trim()));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java JSP