首页 > 其他 > 详细

去掉全角空格和半角空格

时间:2014-02-27 08:40:04      阅读:594      评论:0      收藏:0      [点我收藏+]

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

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

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

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

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

bubuko.com,布布扣
 1 static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
 2         StringBuffer sb = new StringBuffer(source);
 3         while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
 4             sb.deleteCharAt(0);
 5         }
 6         while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
 7                 .toString()) != -1) {
 8             sb.deleteCharAt(sb.length() - 1);
 9         }
10         return sb.toString();
11     }
bubuko.com,布布扣

完整代码:

bubuko.com,布布扣
 1 package com.konglong.test;
 2 
 3 public class TrimTest {
 4     public static void main(String[] args) {
 5         String value = "  俞子东 ";
 6         char[] val = new char[value.length()];
 7         value.getChars(0, value.length(), val, 0);//字符串转换成字符数组
 8 
 9         System.out.println(val.length);
10         
11         System.out.println(value.replaceAll(" | ", ""));
12         
13         System.out.println(myTrim(value, "  "));
14     }
15 
16     static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
17         StringBuffer sb = new StringBuffer(source);
18         while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
19             sb.deleteCharAt(0);
20         }
21         while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
22                 .toString()) != -1) {
23             sb.deleteCharAt(sb.length() - 1);
24         }
25         return sb.toString();
26     }
27 }
bubuko.com,布布扣

去掉全角空格和半角空格,布布扣,bubuko.com

去掉全角空格和半角空格

原文:http://www.cnblogs.com/dfg-09/p/3569071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!