Visit Sponsor

Written by 4:43 pm Core Java

String length and trim string in java

Code snippet explains the usage of String class length and trim() method.

  • The length() method returns the length of this string.
  • The trim() method returns a copy of the string, with leading and trailing whitespace omitted.
import java.util.Scanner;

public class StringExampleTwo {
	public static void main(String args[]) {
		
		Scanner scanner= new Scanner(System.in);
		System.out.println("Enter a string with space");
		
		String s1 = scanner.nextLine();
		System.out.println("s1 = " + s1);

		// Display String Length
		System.out.println("The length of s1 is: " + s1.length());

		// Removing extra spaces from s1
		String s2 = s1.trim();

		System.out.println("s2 = " + s2);
		System.out.println("The length of s2 is: " + s2.length());
	}

}

Visited 7 times, 1 visit(s) today
Close