活动地址:CSDN21天学习挑战赛
题目
给定一个非空字符串S,其被N个‘-’分隔成N+1的子串,给定正整数K,要求除第一个子串外,其余的子串每K个字符组成新的子串,并用‘-’分隔。对于新组成的每一个子串,如果它含有的小写字母比大写字母多,则将这个子串的所有大写字母转换为小写字母;反之,如果它含有的大写字母比小写字母多,则将这个子串的所有小写字母转换为大写字母;大小写字母的数量相等时,不做转换。
输入输出
输入描述:
输入为两行,第一行为参数K,第二行为字符串S。
输出描述:
输出转换后的字符串。
示例1
输入
3
12abc-abCABc-4aB@
输出
12abc-abc-ABC-4aB-@
说明
子串为12abc、abCABc、4aB@,第一个子串保留,后面的子串每3个字符一组为abC、ABc、4aB、@,abC中小写字母较多,转换为abc,ABc中大写字母较多,转换为ABC,4aB中大小写字母都为1个,不做转换,@中没有字母,连起来即12abc-abc-ABC-4aB-@
示例2
输入
12
12abc-abCABc-4aB@
输出
12abc-abCABc4aB@
说明
子串为12abc、abCABc、4aB@,第一个子串保留,后面的子串每12个字符一组为abCABc4aB@,这个子串中大小写字母都为4个,不做转换,连起来即12abc-abCABc4aB@
代码展示
import java.util.Scanner;
public class Day02SplitStr {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//接收长度
int len = in.nextInt();
in.nextLine();
//接收字符串
String str = in.nextLine();
//第一个子串
String last = str.substring(0,str.indexOf("-"));
//拼接后面字符串
String other = str.substring(str.indexOf("-")+1).replace("-","");
//后面字符串重置,StringBuilder利于字符串拼接
StringBuilder s = new StringBuilder();
//按要求分割字符串
if(len>=other.length()){
//格式化字符串
s = new StringBuilder(strFormat(other));
}else {
for (int i = 0; i < other.length(); i=i+len) {
if(i+len>other.length()){
s.append("-").append(strFormat(other.substring(i)));
}else {
s.append("-").append(strFormat(other.substring(i, i + len)));
}
}
}
System.out.println(last+s);
}
//字符串格式化
private static String strFormat(String other) {
int lowerNum = 0; //小写字符计数
int upperNum = 0; //大写字符计数
char[] chars = other.toCharArray();
for (char c : chars) {
if(Character.isLowerCase(c)){
lowerNum++;
}else if(Character.isUpperCase(c)){
upperNum++;
}
}
if(lowerNum>upperNum){
//转化全小写
return other.toLowerCase();
}else if (upperNum>lowerNum){
//转化全大写
return other.toUpperCase();
}else {
return other;
}
}
}
题解
1,大小写转换需要用到字符串api中的toLowerCase()和toUpperCase()方法。
2,字符串切割有split,subString等