欢迎光临
我们一直在努力

移除字符串两边的空格,输入一个字符串去掉其中的空格字符

在比较excel表中两个字符串是否相等的时候,没有注意到前后空格,导致匹配的时候不相等,那么怎么去掉一个字符串的多余空格呢?

第一个方法:java中已有去掉字符串前后空格的方法trm()

测试代码如下:

public static void main(String args[]) { String string = ” hhdh d”;//该字符串前面有两个空格 System.out.println(“字符串为:” + string + “字符串长度为:” + string.length()); string = string.trim(); System.out.println(“去掉首尾空格后的字符串:” + string + “字符串长度为:” + string.length()); }

执行结果为:

第二个方法:自己尝试着写了一个去掉前后空格的方法

代码如下:

public static void main(String args[]) { String string = ” ahshhs “; System.out.println(“字符串为:” + string + “字符串长度为:” + string.length()); string = deleteSpace(string); System.out.println(“去掉首尾空格后的字符串:” + string + “字符串长度为:” + string.length()); } public static String deleteSpace(String string) { if (string == null) { System.out.println(“字符串为空,请重新输出”); } else { for (int i = 0; i < string.length(); i++) { char chars = string.charAt(i); if (chars == ‘ ‘) { string = string.substring(i + 1, string.length() – 1); } else { break; } } for (int j = string.length() – 1; j >= 0; j–) { if (string.charAt(j) == ‘ ‘) { string = string.substring(0, j); } else { break; } } } return string; }

执行结果如下:

其中字符串String的charAt(int index)方法:

是用来去下标为index的美国高防vps字符,以为string就相当于是一个长度为string.length()的字符数组,所以我们可以通过charAt方法来获取某个下标(从0开始)的值,然后判断是否为’ ‘,

若是则利用字符串的另一个方法substring方法:

截取下标加1位置到length-1位置的字符串内容;相同的,若反过来,最后一位是’ ‘则利用substring方法截取0到j位的字符串内容,最终前后位置的空字符全部去掉,中间位置的没有去掉。

28227065

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。