在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1. 把每个单词的首字母变为大写。
2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
3. 把单词中间有多个空格的调整为1个空格。例如:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me WhatCpp_2005_program
用户输入:
this is a 99cat
则程序输出:
This Is A 99_cat
我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。
假设用户输入的串长度不超过200个字符。
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String str = read.readLine();
operator(str);
}
public static void operator(String str) {
String[] strs = str.split(" ");
for (int i = 0; i < strs.length; i++) {
strs[i] = strs[i].trim();
if (strs[i].length() == 0) continue;
String first = String.valueOf(strs[i].charAt(0));
strs[i] = strs[i].replaceFirst(first, first.toUpperCase());
for (int j = 1; j < strs[i].length(); j++) {
char prev = strs[i].charAt(j - 1);
char now = strs[i].charAt(j);
if (now >= '0' && now <= '9') {
if (prev >= 'a' && prev <= 'z' || prev >= 'A' && prev <= 'Z') {
strs[i] = strs[i].substring(0, j) + "_" + strs[i].substring(j);
}
}
if (now >= 'a' && now <= 'z' || now >= 'A' && now <= 'Z') {
if (prev >= '0' && prev <= '9') {
strs[i] = strs[i].substring(0, j) + "_" + strs[i].substring(j);
}
}
}
System.out.print(strs[i] + " ");
}
}