Java String trim() 方法与示例
Java String 中的trim()方法是一个内置函数,可以消除前导和尾随空格。空格字符的 Unicode 值为 '\u0020'。 Java中的 trim() 方法检查字符串前后的 Unicode 值,如果存在则删除空格并返回省略的字符串。 trim() 方法还有助于修剪Java中的字符。
Note: The trim() method doesn’t eliminate middle spaces.
方法签名:
public String trim()
参数: trim() 方法不接受任何参数。
返回类型: trim() 方法的返回类型是String 。它返回没有前导和尾随空格的省略字符串。
下面的示例展示了Java中字符串trim()方法的工作原理。
示例 1:
Java
// Java program to demonstrate working
// of java string trim() method
class Gfg {
// driver code
public static void main(String args[])
{
// trims the trailing and leading spaces
String s = " geeks for geeks has all java functions to read ";
System.out.println(s.trim());
// trims the leading spaces
s = " Chetna loves reading books";
System.out.println(s.trim());
}
}
Java
// Java program to demonstrate working
// of java string trim() method
import java.io.*;
class GFG {
public static void main (String[] args) {
String s1 = " Geeks For Geeks ";
// Before Trim() method
System.out.println("Before Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
// applying trim() method on string s1
s1=s1.trim();
// After Trim() method
System.out.println("\nAfter Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
}
}
输出
geeks for geeks has all java functions to read
Chetna loves reading books
示例 2:
Java
// Java program to demonstrate working
// of java string trim() method
import java.io.*;
class GFG {
public static void main (String[] args) {
String s1 = " Geeks For Geeks ";
// Before Trim() method
System.out.println("Before Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
// applying trim() method on string s1
s1=s1.trim();
// After Trim() method
System.out.println("\nAfter Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
}
}
输出
Before Trim() -
String - Geeks For Geeks
Length - 21
After Trim() -
String - Geeks For Geeks
Length - 15