zoukankan      html  css  js  c++  java
  • Java如何清除空格?

    在Java编程中,如何清除/删除空格?

    以下示例演示如何使用Util.regex.Pattern类的matcher.replaceAll(stringname)方法来删除空格。

    package com.yiibai;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RemovingWhitespaces {
        public static void main(String[] argv) {
            String str = "This is a Java program. This is another Java Program.";
            String pattern = "[\s]";
            String replace = "";
            Pattern p = Pattern.compile(pattern);
            Matcher m = p.matcher(str);
            str = m.replaceAll(replace);
            System.out.println("After Whitespaces trim: "+str);
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    After Whitespaces trim: ThisisaJavaprogram.ThisisanotherJavaProgram.
    
    Shell

    示例-2

    以下是删除空格的另一个示例。

    package com.yiibai;
    
    import java.util.Scanner ;
    import java.lang.String ;
    
    public class RemovingWhitespaces2 {
       public static void main (String[]args) { 
          String s1 = null; 
          Scanner scan = new Scanner(System.in);
          System.out.println("Enter a new string: ");
          s1 = scan.nextLine();
          System.out.println("Input String is  : "+s1);
          String s2 = s1.replaceAll("\s+","");
          System.out.println("Output String is  : "+s2);
       }
    }
    
    Java

    上述代码示例将产生以下结果 -

    Enter a new string: 
    this is a new string with whitespace.
    Input String is  : this is a new string with whitespace.
    Output String is  : thisisanewstringwithwhitespace.
  • 相关阅读:
    Python Socket传输文件
    docker-compose使用volume部署mysql时permission deny问题解决
    Docker-compose ports和expose的区别
    Docker Compose
    Docker Compose 配置文件详解
    SynergyS7G2RTC时钟模块的使用
    Maven 之多模块构建
    Dockerfile 中的 COPY 与 ADD 命令
    Docker Dockerfile 一
    Docker镜像构建上下文(Context)
  • 原文地址:https://www.cnblogs.com/borter/p/9617148.html
Copyright © 2011-2022 走看看