String类的trim()方法返回字符串的副本,并省略前导和尾随空格。
import java.lang.*; public class StringDemo { public static void main(String[] args) { //带有前后空格的字符串 String str = " This is nhooo "; System.out.print("Before trim = "); System.out.println(".." + str + ".."); //删除前导和尾随空白 System.out.print("After trim = "); System.out.println(".." + str.trim() + ".."); } }
输出结果
Before trim = .. This is nhooo .. After trim = ..This is nhooo..