Split string to equal length substrings in Java

后端 未结 21 1863
日久生厌
日久生厌 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: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"]
    

提交回复
热议问题