如何从Java中的字符串中删除前导和尾随空格? [英] How to remove leading and trailing whitespace from the string in Java?

查看:235
本文介绍了如何从Java中的字符串中删除前导和尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中删除前导和尾随空格:

I want to remove the leading and trailing whitespace from string:

String s = "          Hello World                    ";

我希望结果如下:

s == "Hello world";


推荐答案

 s.trim()

参见 String#trim()

没有任何内部方法,请使用正则表达式

Without any internal method, use regex like

 s.replaceAll("^\\s+", "").replaceAll("\\s+$", "")

  s.replaceAll("^\\s+|\\s+$", "")

或只是以纯粹形式使用模式

or just use pattern in pure form

    String s="          Hello World                    ";
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(s);
    StringBuffer out = new StringBuffer();
    while(m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);
    System.out.println(out+"!");

这篇关于如何从Java中的字符串中删除前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆