Java中的Trim()函数可以去除字符串的空白前缀和空白后缀,可用来规范用户输入的内容,具体这样用:
String s=" Hello world ".trim();
然后s就是"Hello world"。
处理名字输入小练:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class testTrim { /** * @param args */ public static void main(String[] args) { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter the name for dealing."); do{ try { str=br.readLine(); str=str.trim();//去掉头尾空格 System.out.println("The name after dealing is "+str); } catch (IOException e) { e.printStackTrace(); System.out.println("ReadLine error!"); break; } }while(!str.equals("stop")); System.out.println("TrimTest Over!"); } }
时间: 2024-10-10 11:03:23