1.问题
Input : str = " Hello World "
Output : str = "Hello World"
Input : str = " Hey there Amy!!! "
Output : str = "Hey there Amy!!!"
2.解题思路
- 借助 trim() 消除 Java 中字符串的前导和尾随空格。
- trim() 方法定义在
java.lang
包的 String
类下。 它不会消除字符串的中间空格
。 - 通过调用 trim() 方法,
返回一个新的 String 对象
。 - 它不会替换 String 对象的值。
- 因此,如果我们想要访问新的 String 对象,我们只需要将它重新分配给旧的 String 或分配给一个新的变量。
3.代码
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 Amy!!! ";
System.out.println(str2);
System.out.println(str2.trim());
}
}
Hello World
Hello World
Hey there Amy!!!
Hey there Amy!!!