Recently, I implemented a process to play with character strings in my work.
Sample.java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Split {
public static void main(String[] args) {
//Theme: Divide a string of length 10 into 5 blocks, 2 characters each
String sampleString = "0123456789";
List<String> splitedStringList = new ArrayList<String>();
Matcher m = Pattern.compile("[\\s\\S]{1,2}").matcher(sampleString);
while (m.find()) {
splitedStringList.add(m.group());
}
for (String element : splitedStringList) {
System.out.println(element); //01 23 45 76 89 is displayed with line breaks
}
}
}
If you make full use of what it is a regular expression, you can write a process like ↑ that "it seems to do something cool at first glance".
Or rather, I made that kind of implementation at first.
This is because split () is based on the delimiter specified in the argument, so you cannot specify "X characters at a time".
However, from the on-site leader who passed behind
"Should I use substring ()?"
After all, it's enough because it only separates strings with super-simple rules. However, the idea of using it during implementation did not come up at all. It's embarrassing.
Even with one implementation, there are many things to consider, such as processing performance and code readability ...
Not limited to Java, it was a case that I should personally reflect on.
Recommended Posts