Java教程

java将字符串分成" N"个相等的部分。

这里,我们的任务是将字符串S分为n个相等的部分。如果无法将字符串分成n个相等的部分,我们将打印一条错误消息,否则所有部分都需要作为程序的输出进行打印。
检查字符串是否可以分为N个相等的部分,我们需要将字符串的长度除以n,然后将结果分配给变量char。
如果char出来的是浮点值,则无法将字符串除,否则运行循环遍历字符串并在每个字符间隔处分割字符串。
该程序的算法如下。

算法

步骤1: START 步骤2: DEFINE str ="aaaabbbbcccc" 步骤3: 定义 len 步骤4: SET n = 3 步骤5: SET temp = 0。 步骤6: chars = len/n 步骤7: DEFINE String [] equalstr。 步骤8: 如果IF(len%n!= 0)
然后进行PRINT("String can't be divided into equal parts")
否则请转到步骤9
步骤9: SET i = 0。 步骤10: 直到i < len 重复步骤11至步骤14 步骤11: DEFINE子字符串部分。 步骤12: equalstr[temp] = part 步骤13: temp = temp + 1 步骤14: i = i + chars 步骤15: 打印n 步骤16: SET i = 0。直到 i < equalstr.length 重复执行步骤17至步骤18 步骤17: 打印equalstr[i] 步骤18: i = i + 1 STEP 19: END

程序:

public class DivideString {
    public static void main(String[] args) {
        String str = "aaaabbbbcccc";
        //Stores the length of the string
        int len = str.length();
        //n determines the variable that divide the string in 'n' equal parts
        int n = 3;
        int temp = 0, chars = len/n;
        //Stores the array of string
        String[] equalStr = new String [n];
        //Check whether a string can be divided into n equal parts
        if(len % n != 0) {
            System.out.println("Sorry this string cannot be divided into "+ n +" equal parts.");
        }
        else {
            for(int i = 0; i < len; i = i+chars) {
                //Dividing string in n equal part using substring()
                String part = str.substring(i, i+chars);
                equalStr[temp] = part;
                temp++;
            }
            System.out.println(n + " equal parts of given string are ");
            for(int i = 0; i < equalStr.length; i++) {
                System.out.println(equalStr[i]);
            }
        }
    }
}
输出:
3 equal parts of given string are
aaaa
bbbb
cccc
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4