[Java] The story that the expected array was not obtained by the String.split method.

Introduction

Java's String method has a split method. By using this method, for example, you can divide a character string at an arbitrary character and generate an array with the divided elements.

example1.java


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //The string you want to make into an array
        String str = "Apple,Orange,banana,watermelon,melon";
        //Specify the character to be used for division
        String[] strArray = str.split(",");
        for(int i = 0; i < strArray.length; i++) {
            System.out.println((i + 1) + ":" + strArray[i]);
        }
    }
}

When you run this source

1: Apple 2: Mandarin orange 3: Banana 4: Watermelon 5: Melon

The result is obtained. Now, the split method, but what if the characters used for splitting are consecutive, as in the following example?

example2.java


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //The string you want to make into an array
        String str = "Apple,Orange,,,";
        //Specify the character to be used for division
        String[] strArray = str.split(",");
        for(int i = 0; i < strArray.length; i++) {
            System.out.println((i + 1) + ":" + strArray[i]);
        }
    }
}

When you run this source

1: Apple 2: Mandarin orange 3: 4: 5:

I was expecting to get the result, but it wasn't.

1: Apple 2: Mandarin orange

Has been displayed. In other words, what it means is that the size of the array obtained in ʻexample2.javawill be 2 instead of 5. In the above example, I thought that the size of the array would be 5 if I used thesplit` method, but when I actually used it in my business, it was not as expected and I was disappointed.

solution

So how did I get what I expected? In conclusion, specify -1 (negative number) as the second argument of the split method as shown in the example below.

example3.java


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //The string you want to make into an array
        String str = "Apple,Orange,,,";
        //In the second argument-Specify 1
        String[] strArray = str.split(",", -1);
        for(int i = 0; i < strArray.length; i++) {
            System.out.println((i + 1) + ":" + strArray[i]);
        }
    }
}

By specifying -1 as the second argument,

1: Apple 2: Mandarin orange 3: 4: 5:

I got the result, and I was able to get the size of the array by the number divided by commas.

What i learned

In solving this problem, I read the Official Document and found two things. I was able to learn.

The first is that the split method does not split by the string specified by the first argument, but correctly by the ** regular expression ** specified by the first argument.

I was convinced that it would be divided by the specified character string, but I realized that it is possible to divide the character string under more complicated conditions by making full use of regular expressions.

The second is to specify a negative number in the second argument of the split method when the strings you want to split are consecutive as in the above example. The second argument of the split method represents the split threshold. If the second argument is not specified, it will be treated the same as if 0 is specified for the second argument. In this case, if the result of dividing in order is an empty string, it will be discarded. So in ʻexample2.java`, the size of the split array is now 2 instead of 5. To prevent this, I found that it is necessary to specify a negative number for the second argument so that the number of divisions is unlimited and the empty string is not discarded.

in conclusion

I was able to reaffirm the importance of referring to the official document when solving this problem. And I was able to realize the importance of using the method after understanding exactly what kind of processing is being performed. I hope this article helps someone.

Recommended Posts

[Java] The story that the expected array was not obtained by the String.split method.
The story that the variable initialization method called in the Java constructor should not be overridden
Was that so, the user_signed_in? method
The story of not knowing the behavior of String by passing Java by reference
The story received by Java SE11 silver
The story that the Servlet could not be loaded in the Java Web application
The story that I could not build after installing multiple Java on Windows
Command that the registered information was not found
[Spring Boot] The story that the bean of the class with ConfigurationProperties annotation was not found
Read the packet capture obtained by tcpdump in Java
The story that the forced update could not be implemented
The story that .java is also built in Unity 2018
The story that the performance increased by 9.26 times when the layout method of View was changed from AutoLayout to warm hand calculation.
The story that the request parameter from the iPhone application could not be obtained successfully with the Servlet
The version of Ruby that was installed by default on the Mac was referenced, not from rbenv
The story when the test folder was not created in Rails
Summary of values returned by the Spliterator characteristics method #java
I passed Oracle's java silver (version 11), so I wrote the flow until I passed by a study method that does not use any writing tools
[Java Silver] Array generation method
[Gradle] The story that the class file did not exist in the jar file
[Java] I tried to make a maze by the digging method ♪
The operator that was born to be born, instanceof (Java) ~ How to use the instanceof operator ~
The story that the build error did not stop when using Eclipse 2020
The story that ARM's processing performance of Open JDK was low
The story of making it possible to build a project that was built by Maven with Ant