如何去掉字符串中的首尾空格

创建类Example,在main()方法中实现通过去掉字符串“ ABC ”中的首尾空格,将得到一个新的字符串“ABC”。

运行结果:

Eclipse中运行Example类,结果如图1所示。

  1  Example类的运行结果

解题关键:

l         String类的trim()方法用于去除字符串中的空格。

l         String类的length()方法获取字符串的长度。

答案:

Example.java文件代码如下:

public class Example {

   public static void main(String[] args) {

      // 定义一个字符串,首尾均有空格

      String str = " ABC ";

      // 输出字符串的长度为5

      System.out.println(str + "长度为 : " + str.length());

      // 去掉字符串的首尾空格

      String str2 = str.trim();

      // 输出字符串的长度为3

      System.out.println(str2 + "长度为 : " + str2.length());

   }

}