2、蓝桥杯之串的简单处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sword_anyone/article/details/89071126

串的处理
在实际的开发工作中,对字符串的处理是最常见的编程任务。
本题目即是要求程序对用户输入的串进行处理。具体规则如下:

  1. 把每个单词的首字母变为大写。
  2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
  3. 把单词中间有多个空格的调整为1个空格。
    例如:
    用户输入:
    you and me what cpp2005program
    则程序输出:
    You And Me What Cpp_2005_program
    用户输入:
    this is a 99cat
    则程序输出:
    This Is A 99_cat
    我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。
    每个单词间由1个或多个空格分隔。
    假设用户输入的串长度不超过200个字符。

package exe1_5;

public class Exe2 {

	static String str[] = {
//		"you and     me what  cpp2005program",
//		"this is     a      99cat",
		"6sdfadsf4 d d1f  d1f2d"
	};

	public static void main(String[] args) {
		change(str);
		print(str);
	}

	private static void print(String[] str2) {
		for(String s:str2)
		{
			System.out.println(s);
		}
	}

	private static void change(String[] str2) {
		for (int i = 0; i < str2.length; i++) {
			StringBuffer sb = new StringBuffer();
			StringBuffer link = new StringBuffer();
			String words[]  = str2[i].trim().split("\\d+");
			String number[] = str2[i].trim().split("\\D+");
			for (int j = 0; j < words.length-1; j++) {
				if (!words[j].endsWith(" ")) {
					link.append(words[j]+"_"+number[j+1]);
				}
				else {
					link.append(words[j]+number[j+1]);
				}
			}
			if (!words[words.length-1].startsWith(" ")) {
				link.append("_"+words[words.length-1]);
			}
			str2[i] = link.toString();    //上面是对数字的处理
			
			
			String splitString[]= str2[i].split("[ ]+");
			for (int j = 0; j < splitString.length; j++) {
				splitString[j] = String.valueOf(splitString[j].toUpperCase().charAt(0))+splitString[j].substring(1);
				sb.append(splitString[j]);
				if (splitString.length-1!=j) {
					sb.append(" ");
				}
			}
			str2[i] = sb.toString();        //上面是对字符的处理
		}
	}

}

支付宝扫红包,让我能够买杯咖啡,继续创作,谢谢大家!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sword_anyone/article/details/89071126
今日推荐