java - after splitting a string, what is the first element in the array?

后端 未结 4 1440
执笔经年
执笔经年 2021-01-11 16:30

I was trying to split a string into an array of single letters. Here\'s what I did,

String str = \"abcddadfad\"; 
System.out.println(str.length());    //  ou         


        
4条回答
  •  失恋的感觉
    2021-01-11 17:18

    Consider the split expression ",1,2,3,4".split(",");

    What would you expect? Right, an empty-string to start with. In your case you have a 'nothing' in front of the first 'a' as well as one behind it.

    Update: comments indicate this explanation is not enough of an explanation (which it may not be)... but, it really is this simple: the engine starts at the beginning of the string, and it looks to see if what's in front of it matches the pattern. If it does, it assigns what's behind it to a new item in the split.

    On the first character, it has "" (nothing behind it), and it looks to see if there's "" (the pattern) in front of it. There is, so it creates a "" match.

    It then moves on, and it has 'a' behind it, and again, it again has "" in front of it. So the second result is an "a" string.

    An interesting observation is that, if you use split("", -1) you will also get an empty-string result in the last position of the result array.


    Edit 2: If I wrack my brains further, and consider this to be an academic exercise (I would not recommend this in real life...) I can think of only one good way to do a regex split() of a String into a String[] array with 1 character in each string (as opposed to char[] - which other people have given great answers for....).

    String[] chars = str.split("(?<=.)", str.length());
    

    This will look behind each character, in a non-capturing group, and split on that, and then limit the array size to the number of characters (you can leave the str.length() out, but if you put -1 you will get an extra space at the end)

    Borrowing nitro2k01's alternative (below in the comments) which references the string beginning and end, you can split reliably on:

    String[] chars = str.split("(?!(^|$))");
    

提交回复
热议问题