Split string to equal length substrings in Java

后端 未结 21 1822
日久生厌
日久生厌 2020-11-22 02:56

How to split the string \"Thequickbrownfoxjumps\" to substrings of equal size in Java. Eg. \"Thequickbrownfoxjumps\" of 4 equal size should give th

相关标签:
21条回答
  • 2020-11-22 03:29
    public static String[] split(String input, int length) throws IllegalArgumentException {
    
        if(length == 0 || input == null)
            return new String[0];
    
        int lengthD = length * 2;
    
        int size = input.length();
        if(size == 0)
            return new String[0];
    
        int rep = (int) Math.ceil(size * 1d / length);
    
        ByteArrayInputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_16LE));
    
        String[] out = new String[rep];
        byte[]  buf = new byte[lengthD];
    
        int d = 0;
        for (int i = 0; i < rep; i++) {
    
            try {
                d = stream.read(buf);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            if(d != lengthD)
            {
                out[i] = new String(buf,0,d, StandardCharsets.UTF_16LE);
                continue;
            }
    
            out[i] = new String(buf, StandardCharsets.UTF_16LE);
        }
        return out;
    }
    
    0 讨论(0)
  • 2020-11-22 03:30
    public static String[] split(String src, int len) {
        String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
        for (int i=0; i<result.length; i++)
            result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 03:31

    You can use substring from String.class (handling exceptions) or from Apache lang commons (it handles exceptions for you)

    static String   substring(String str, int start, int end) 
    

    Put it inside a loop and you are good to go.

    0 讨论(0)
  • 2020-11-22 03:31

    A StringBuilder version:

    public static List<String> getChunks(String s, int chunkSize)
    {
     List<String> chunks = new ArrayList<>();
     StringBuilder sb = new StringBuilder(s);
    
    while(!(sb.length() ==0)) 
    {           
       chunks.add(sb.substring(0, chunkSize));
       sb.delete(0, chunkSize);
    
    }
    return chunks;
    

    }

    0 讨论(0)
  • 2020-11-22 03:32

    Well, it's fairly easy to do this with simple arithmetic and string operations:

    public static List<String> splitEqually(String text, int size) {
        // Give the list the right capacity to start with. You could use an array
        // instead if you wanted.
        List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
    
        for (int start = 0; start < text.length(); start += size) {
            ret.add(text.substring(start, Math.min(text.length(), start + size)));
        }
        return ret;
    }
    

    I don't think it's really worth using a regex for this.

    EDIT: My reasoning for not using a regex:

    • This doesn't use any of the real pattern matching of regexes. It's just counting.
    • I suspect the above will be more efficient, although in most cases it won't matter
    • If you need to use variable sizes in different places, you've either got repetition or a helper function to build the regex itself based on a parameter - ick.
    • The regex provided in another answer firstly didn't compile (invalid escaping), and then didn't work. My code worked first time. That's more a testament to the usability of regexes vs plain code, IMO.
    0 讨论(0)
  • 2020-11-22 03:32

    Here is my version based on RegEx and Java 8 streams. It's worth to mention that Matcher.results() method is available since Java 9.

    Test included.

    public static List<String> splitString(String input, int splitSize) {
        Matcher matcher = Pattern.compile("(?:(.{" + splitSize + "}))+?").matcher(input);
        return matcher.results().map(MatchResult::group).collect(Collectors.toList());
    }
    
    @Test
    public void shouldSplitStringToEqualLengthParts() {
        String anyValidString = "Split me equally!";
        String[] expectedTokens2 = {"Sp", "li", "t ", "me", " e", "qu", "al", "ly"};
        String[] expectedTokens3 = {"Spl", "it ", "me ", "equ", "all"};
    
        Assert.assertArrayEquals(expectedTokens2, splitString(anyValidString, 2).toArray());
        Assert.assertArrayEquals(expectedTokens3, splitString(anyValidString, 3).toArray());
    }
    
    0 讨论(0)
提交回复
热议问题