Split string to equal length substrings in Java

后端 未结 21 1821
日久生厌
日久生厌 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:34

    Java 8 solution (like this but a bit simpler):

    public static List<String> partition(String string, int partSize) {
      List<String> parts = IntStream.range(0, string.length() / partSize)
        .mapToObj(i -> string.substring(i * partSize, (i + 1) * partSize))
        .collect(toList());
      if ((string.length() % partSize) != 0)
        parts.add(string.substring(string.length() / partSize * partSize));
      return parts;
    }
    
    0 讨论(0)
  • 2020-11-22 03:36

    I'd rather this simple solution:

    String content = "Thequickbrownfoxjumps";
    while(content.length() > 4) {
        System.out.println(content.substring(0, 4));
        content = content.substring(4);
    }
    System.out.println(content);
    
    0 讨论(0)
  • 2020-11-22 03:36
        import static java.lang.System.exit;
       import java.util.Scanner;
       import Java.util.Arrays.*;
    
    
     public class string123 {
    
    public static void main(String[] args) {
    
    
      Scanner sc=new Scanner(System.in);
        System.out.println("Enter String");
        String r=sc.nextLine();
        String[] s=new String[10];
        int len=r.length();
           System.out.println("Enter length Of Sub-string");
        int l=sc.nextInt();
        int last;
        int f=0;
        for(int i=0;;i++){
            last=(f+l);
                if((last)>=len) last=len;
            s[i]=r.substring(f,last);
         // System.out.println(s[i]);
    
          if (last==len)break;
           f=(f+l);
        } 
        System.out.print(Arrays.tostring(s));
        }}
    

    Result

     Enter String
     Thequickbrownfoxjumps
     Enter length Of Sub-string
     4
    
     ["Theq","uick","brow","nfox","jump","s"]
    
    0 讨论(0)
提交回复
热议问题