Java string length examples

The lenght of java string can be get very easu by method: length() which is without parameters. You can do some tricks if you want to get the lenght without white spaces or only the letters. In this post:

  • basic string lenght
  • string length no spaces
  • string length of letters
  • string length of numbers inside the string

More about regex and strings in java:

Java string length basic example

Basic usage of string length in java. There's no change in last versions of java:

String str1="Java";
String str2="This is a " + " joined string";
System.out.println("str1 length is: "+str1.length());//4
System.out.println("str2 length is: "+str2.length());//24

result:

str1 length is: 4
str2 length is: 24

Java string length without spaces

You can do a simple trick in order to skip white spaces in calculating the length of the string:

String str = "   I  have   some   extra spaces.. ";

System.out.println("spaces: "+str.length());
System.out.println("No spaces: " + str.replace(" ", "").length());

result:

spaces: 35
No spaces: 22

Java string length only letters

If you want to get the lenght of the string only counting the letters inside then you can use a regex to replace all non letter characters like:

str.replaceAll("[^a-zA-Z]", "")

example:

String str = "   I  have   some   extra spaces.. 12312314 !!! >< ";
System.out.println("all: "+str.length());
System.out.println("Letters: " + str.replaceAll("[^a-zA-Z]", "").length());

result:

all: 51
Letters: 20

Java string length only numbers

If you need to count only the number as string length then you can use regex:

str.replaceAll("[^\\d]", "")

example:

String str = "   I  have   some   extra spaces.. 12312314 !!! >< ";
System.out.println("all: "+str.length());
System.out.println("Numbers: " + str.replaceAll("[^\\d]", "").length());

result:

all: 51
Numbers: 8

Related Article