java实现字符串按照规则分割

文章讲述了如何使用Java编程语言实现字符串分割功能,当满足特定条件(子串长度为K且大小写字母数量不同时)对子串进行大小写转换,提供了一个示例代码片段。
摘要由CSDN通过智能技术生成

java实现字符串分割


描述

给定一个非空字符串S,其被N个“分隔成N+1的子串,给定正整数K,要求除第一个子串外,其余的子串每K个字符组成新的子串,并用“分隔。
对于新组成的每一个子串,如果它含有的小写字母比大写字母多,则将这个子串的所有大写字母转换为小写字母:反之,如果它含有的大写字母比小写字母多,则将这个子串的所有小写字母转换为大写字母;大小写字母的数是相等时,不做转换。

输入描述
输入为两行,第一行为参数K,第二行为字符串S。

输出描述
输出转换后的字符串。

用例:
输入:12abc-abCABc-4aB@
3
输出:12abc-abc-ABC-4aB-@

输入:12abc-abCABc-4aB@
12
输出:12abc-abCABc4aB@

java实现(开箱即用)

package com.des.data.test;

public class StringSegmentation {

    public static void main(String[] args) {
        String str1 = "12abc-abCABc-4aB@";
        String Str2 = "12abc-abCABc-4aB@";
        System.out.println(split(str1, 12));
    }

    public static String split(String str, int k) {
        StringBuffer res = new StringBuffer();
        String[] strings = str.split("-");

        StringBuffer stb = new StringBuffer();
        for (int i = 0; i < strings.length; i++) {
            if (i == 0) {
                continue;
            }
            stb.append(strings[i]);
        }
        res.append(strings[0]).append("-");
        String stbz = stb.toString();
        int end = 1;
        for (int i = 0; i < stbz.length(); i++) {
            res.append(stbz.charAt(i));
            if (end == k) {
                res.append("-");
                end = 1;
            } else {
                end++;
            }
        }
        System.out.println();
        String[] strFen = res.toString().split("-");
        StringBuffer resN = new StringBuffer();
        for (int i = 0; i < strFen.length; i++) {
            String sfs = strFen[i];
            if (i == 0) {
                resN.append(sfs).append("-");
                continue;
            }
            int up = 0;
            int low = 0;
            for (int j = 0; j < sfs.length(); j++) {
                char c = sfs.charAt(j);
                if (Character.isUpperCase(c)) {
                    up++;
                }
                if (Character.isLowerCase(c)) {
                    low++;
                }
            }
            if (low > up) {
                String sfsn = sfs.toLowerCase();
                resN.append(sfsn).append("-");
            }
            if (up > low) {
                String sfsn = sfs.toUpperCase();
                resN.append(sfsn).append("-");
            }
            if (up == low) {
                resN.append(sfs).append("-");
            }
        }
        String resStr = resN.toString();
        return resStr.substring(0, resStr.length() - 1);
    }
}
  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值