• java去全半角空格,trim(), replaceAll(" +",""),replaceAll("\s*", ""), replaceAll(" | ", "")


    JAVA中去掉空格  
     
    1. String.trim() 
    trim()是去掉首尾空格 
     
    2.str.replace(" ", ""); 去掉所有空格,包括首尾、中间 
    String str = " hell o "; 
    String str2 = str.replaceAll(" ", ""); 
    System.out.println(str2); 
    
    3.或者replaceAll(" +",""); 去掉所有空格 
    
    4.str = .replaceAll("\s*", ""); 
    可以替换大部分空白字符, 不限于空格  
    s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 
    
    
    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();
        }
    }
    
     
  • 相关阅读:
    Web应用程序的开发步骤
    APAP INCLUDE
    2015-07-12
    oracle自定义异常
    java quartz 设置定时任务串行执行
    java stream peek的使用
    java List转String
    Java打jar包后如何获取resource中的文件
    ImmutablePair和ImmutableTriple的使用
    mvn打jar包示例:依赖打入jar包和依赖打到外部文件夹
  • 原文地址:https://www.cnblogs.com/timssd/p/5008889.html
Copyright © 2020-2023  润新知