Written in ** JDK 1.8 **.
Substring
of the String
classThe String
class has a substring
method that cuts out part of a string. It will cut out two types according to the number of arguments.
** Definition **
substring(int beginIndex)
It cuts out the characters after beginIndex
. Note that the string index counts from 0
.
Example of use
String str = ("Doraemon");
String cutStr = str.substring(2);
System.out.println("After cutting:" + cutStr);
result
After cutting: Emon
The character string after the character e
in the specified index 2
is cut out.
** Definition **
substring(int beginIndex, int endIndex)
It cuts out the characters after beginIndex
including the characters of ʻendIndex-1`.
Example of use
String str = ("Doraemon");
String cutStr = str.substring(2, 4);
System.out.println("After cutting:" + cutStr);
result
After cutting: Emo
The character string Emo
from the specified beginIndex = 2
to the character E
at ʻendIndex --1 = 3` is cut out.
If there are two arguments and the string is less than ʻendIndex -1`, an exception will be thrown.
Output the character string to be displayed on the screen. Since there is a limit that only 4 characters can be displayed on the screen, I want to limit the output character string to 4 characters. If the character string is less than 4 characters, I want to output it as it is.
code
String str1 = ("Doraemon");
String str2 = ("Nobita");
String str3 = ("Suneo");
List<String> sourceStrList = Arrays.asList(str1, str2, str3);
List<String> outStrList = new ArrayList<>();
for (String sourceStr : sourceStrList) {
outStrList.add(sourceStr.substring(0, 4));
}
System.out.println("After cutting:" + outStrList);
result
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
Yes, an exception has occurred. Here, Nobita
and Suneo
have indexes up to 2
, so they are exceptions because they are less than ʻendIndex -1 = 3`.
It is troublesome because it is necessary to check the character length in advance to solve it.
substring
in StringUtils
If you use the substring
provided in ʻorg.apache.commons.lang3.StringUtils`, you will be able to solve this problem.
substring(String str, int start, int end)
The character string whose index of the character string to be cut out in str
is start
to ʻend -1` is output.
code
String str1 = ("Doraemon");
String str2 = ("Nobita");
String str3 = ("Suneo");
List<String> sourceStrList = Arrays.asList(str1, str2, str3);
List<String> outStrList = new ArrayList<>();
for (String sourceStr : sourceStrList) {
outStrList.add(StringUtils.substring(sourceStr, 0, 4));
}
System.out.println("After cutting out:" + outStrList);
result
After cutting out[Doraemon,Nobita,Suneo]
Even if the character string is less than ʻend --1 = 3`, it will be output as it is.
java.lang String substring org.apache.commons.lang3 Class StringUtils substring
Recommended Posts