大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Java技巧 > java去掉全角空格和半角空格

java去掉全角空格和半角空格

关键词:全角空格半角java  阅读(3908) 赞(12)

[摘要]

本文主要讲解了java去掉全角空格和半角空格的方法,与大家共享。

需求1:将字符串转换成字符数组

 String value = "  俞子东 ";
         char[] val = new char[value.length()];
         value.getChars(0, value.length(), val, 0);//字符串转换成字符数组
 
         System.out.println(val.length)

需求2:将所有的全角空格和半角空格去掉

 System.out.println(value.replaceAll(" | ", ""));

需求3:将字符串两边的半角空格、全角空格去掉(调用myTrim(value, "  ");)

 static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
         StringBuffer sb = new StringBuffer(source);
         while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
             sb.deleteCharAt(0);
         }
         while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
                 .toString()) != -1) {
             sb.deleteCharAt(sb.length() - 1);
         }
         return sb.toString();
     }

完整代码:

 package com.konglong.test;
 
 public class TrimTest {
     public static void main(String[] args) {
         String value = "  俞子东 ";
         char[] val = new char[value.length()];
         value.getChars(0, value.length(), val, 0);//字符串转换成字符数组
 
         System.out.println(val.length);
         
         System.out.println(value.replaceAll(" | ", ""));
         
         System.out.println(myTrim(value, "  "));
     }
 
     static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
         StringBuffer sb = new StringBuffer(source);
         while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
             sb.deleteCharAt(0);
         }
         while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
                 .toString()) != -1) {
             sb.deleteCharAt(sb.length() - 1);
         }
         return sb.toString();
     }
 }


相关评论