Let`s see how to calculate the length of a string in Java.
Strings
length()` returns the length of the string.
// String.java
public int length()
Because it returns the length of a Unicode string, it can be used for strings in other languages as well.
Returns the length of a string as follows.
String str1 = "Hello";
String str2 = "안녕하세요";
String str3 = "こんにちは";
System.out.println(str1.length());
System.out.println(str2.length());
System.out.println(str3.length());
Output:
5
5
5
Trim String: subString()
If you want to limit the length of a string to 20, you can truncate the string with subString()
.
String str = "The length is equal to the number of 16-bit Unicode characters in the string.";
System.out.println("origin length() : " + str.length());
String subString = str.substring(0, 20);
System.out.println("substring : " + subString);
System.out.println("substring length() : " + subString.length());
Output:
origin length() : 77
substring : The length is equal
substring length() : 20
subString()
takes two arguments and returns a string containing beginIndex and no endIndex.
So the above code substring(0, 20)
truncates the string from index 0 to 19 and returns it.
// String.java
public String substring(int beginIndex, int endIndex)
If you want to cut a string and append ...
, you can paste it as follows. trim()
is a method that trims whitespace in a string.
String str = "The length is equal to the number of 16-bit Unicode characters in the string.";
System.out.println("origin length() : " + str.length());
String subString = str.substring(0, 20);
subString = subString.trim() + "...";
System.out.println("substring : " + subString);
System.out.println("substring length() : " + subString.length());
Output:
origin length() : 77
substring : The length is equal...
substring length() : 22
Difference between length, length() and size()
size()
is used to get the length of Collections such as List.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Wiki");
System.out.println("List size : " + list.size());
Output:
List size : 2
length
is used to get the length of an Array. Unlike Strings
length()`, it is not a function.
As shown below, length can be used to find the length of an Array and length()
can be used to find the length of a String.
String[] strArray = new String[] {
"Apple", "Kiwi", "Cherry", "Peach", "Grape"};
System.out.println("Array length : " + strArray.length);
for (String str : strArray) {
System.out.println("string : " + str);
System.out.println("length() : " + str.length());
}
Output:
Array length : 5
string : Apple
length() : 5
string : Kiwi
length() : 4
string : Cherry
length() : 6
string : Peach
length() : 5
string : Grape
length() : 5
string length limit
If you want to discard strings that exceed a certain length, you can exclude them with an if
statement as shown below.
String[] strArray = new String[] {
"Apple", "Kiwi", "Cherry", "Peach", "Grape"};
for (String str : strArray) {
if (str.length() <= 5) {
System.out.println("string : " + str);
System.out.println("length() : " + str.length());
}
}
Output:
string : Apple
length() : 5
string : Kiwi
length() : 4
string : Peach
length() : 5
string : Grape
length() : 5
The above code can also be implemented using a Stream like this:
String[] strArray = new String[] {
"Apple", "Kiwi", "Cherry", "Peach", "Grape"};
Arrays.stream(strArray)
.filter((str) -> str.length() <= 5)
.forEach((str) -> {
System.out.println("string : " + str);
System.out.println("length() : " + str.length());
});
Output:
string : Apple
length() : 5
string : Kiwi
length() : 4
string : Peach
length() : 5
string : Grape
length() : 5
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)