📌  相关文章
📜  修剪(删除前导和尾随空格) Java中的字符串

📅  最后修改于: 2022-05-13 01:55:21.361000             🧑  作者: Mango

修剪(删除前导和尾随空格) Java中的字符串

给定一个字符串,从字符串中删除所有前导和尾随空格并返回它。

例子:

Input :  str = "   Hello World   "
Output : str = "Hello World"

Input :  str = "      Hey  there    Joey!!!      "
Output : str = "Hey  there    Joey!!!"
  • 我们可以借助trim()消除Java中字符串的前导和尾随空格。
  • trim() 方法定义在Java.lang 包的 String 类下。
  • 它不会消除字符串的中间空格。
  • 通过调用 trim() 方法,返回一个新的 String 对象。
  • 它不会替换 String 对象的值。因此,如果我们想要访问新的 String 对象,我们只需要将它重新分配给旧的 String 或将它分配给一个新的变量。

这个怎么运作?
对于空格字符,unicode 值为 '\u0020'。此方法在字符串之前和之后检查此 unicode 值,如果存在则消除空格(前导和尾随)并返回字符串(没有前导和尾随空格)。

public class remove_spaces
{
    public static void main(String args[])
    {
        String str1 = "  Hello World  ";
        System.out.println(str1);
        System.out.println(str1.trim());
  
        String str2 = "      Hey  there    Joey!!!      ";
        System.out.println(str2);
        System.out.println(str2.trim());
    }
}

输出:

Hello World  
Hello World
      Hey  there    Joey!!!  
Hey  there    Joey!!!