Java.trim()详解

发布时间:2023-05-20

一、trim()方法简介

在JAVA中,trim()方法可以去掉一个字符串的首尾空格

String str = " hello world ";
String trimStr = str.trim(); // trimStr = "hello world"

从上面的例子中,我们可以看到trim()方法去除了字符串首尾的空格,并返回了新的字符串。

二、trim()方法的使用场景

1、去除表单输入的空格

// 用户输入的数据
String username = request.getParameter("username").trim();
String password = request.getParameter("password").trim();

在表单输入的时候,用户可能会在输入的两端加上一个或多个空格,如果不使用trim()方法处理的话,这些无用的空格将作为字符串的一部分进行存储,导致一些不必要的错误。 2、取出配置文件中的值

Properties prop = new Properties();
InputStream is = new FileInputStream("config.properties");
prop.load(is);
String name = prop.getProperty("name").trim();
String url = prop.getProperty("url").trim();

在读取配置文件时,可能会出现值中包含了多余空格的情况,使用trim()方法可以有效去除这些空格。

三、trim()方法的注意事项

1、不会去除中间的空格

String str = "hello   world";
String trimStr = str.trim(); // trimStr = "hello   world"

从上面的例子中,我们可以看到trim()方法只会去除字符串首尾的空格,而不会去除字符串中间的空格。 2、不能去除其他不可见字符

String str1 = "\t hello world \t";
String str2 = "\n hello world \n";
String trimStr1 = str1.trim(); // trimStr1 = "\t hello world \t"
String trimStr2 = str2.trim(); // trimStr2 = "\n hello world \n"

从上面的例子中,我们可以看到trim()方法只能去掉字符串首尾的空格,对于其他不可见字符如换行符、制表符等则不能去除。

四、其他字符串操作方法

1、equals()方法比较字符串是否相等

String str1 = "hello";
String str2 = "hello";
if(str1.equals(str2)) {
    System.out.println("str1和str2相等");
} else {
    System.out.println("str1和str2不相等");
}

2、concat()方法连接两个字符串

String str1 = "hello";
String str2 = "world";
String str3 = str1.concat(str2); // str3 = "helloworld"

3、indexOf()方法查找字符串中第一个匹配子串的位置

String str = "hello world";
int index = str.indexOf("world"); // index = 6

4、substring()方法提取字符串的一部分

String str = "hello world";
String subStr = str.substring(6); // subStr = "world"

五、总结

从本文的介绍中,我们了解了trim()方法的使用场景和注意事项,同时还介绍了其他一些常用的字符串操作方法。在实际开发中,对于字符串的处理,我们需要根据具体情况进行选择和应用。