public class DeleteBlank { public static void main(String[] args) { //定义一个带空格的字符串 String a = " 2 3 41 2 4 45"; //用trim() 方法去空格 System.out.println("字符串:"+a+"\n\n去空格:"+a.trim()); String[] split = new String[a.length()]; //拆分字符串,存到 split 数组里 for (int i=0; i<a.length(); i++) { split[i] = a.substring(i, i+1); } String x = "0"; //去掉空格后的字符串 for (int i=0; i<a.length(); i++) { if (split[i].equals(" ")) { continue; } else { x=x+split[i]; //把拆分的每一个都加上去,拼成一个没有空格的新字符串。 } } String x1 = x.substring(1); //去掉默认的 0 int x2 = Integer.parseInt(x1); //转换为 int 型数据 System.out.println("\n去全部空格:"+x1); System.out.println("\n转为int型:"+x2); System.out.println("\n乘2得:"+x2*2);
//方法2
String a1 = a.replace(" ", "");
int x3 = Integer.parseInt(a1);
System.out.println("\n\n转为int型:"+x3);
System.out.println("\n乘2得:"+x3*2); } }
转载于:https://www.cnblogs.com/daidai-99/p/4224216.html