在实际的开发工作中,对字符串的处理是最常见的编程任务 这次我要做的就是对给定字符串进行处理 具体处理规则如下:
- 把每个单词的首字母变为大写
- 把数字与字母之间用下划线字符
_ 分开,使得更清晰 - 把每个单词之间多个空白符变为一个
举例:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me What Cpp_2005_program
用户输入:
this is a 99cat
则程序输出:
This Is A 99_cat
接下来看实现代码
static String format(String str) {
String[] words = str.split("\\s+");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < words.length; i++) {
char ch = words[i].charAt(0);
if (ch >= 'a' && ch <= 'z') {
ch = (char) (ch - 32);
}
words[i] = words[i].replace(words[i].charAt(0), ch);
StringBuffer sb2 = new StringBuffer();
for (int j = 0; j < words[i].length(); j++) {
if (words[i].charAt(j) >= '0' && words[i].charAt(j) <= '9') {
if (j != 0) {
if (words[i].charAt(j - 1) >= 'a' && words[i].charAt(j - 1) <= 'z' || words[i].charAt(j - 1) >= 'A' && words[i].charAt(j - 1) <= 'Z') {
sb2.append("_");
}
}
if (j + 1 < words[i].length()) {
if (words[i].charAt(j + 1) >= 'a' && words[i].charAt(j + 1) <= 'z' || words[i].charAt(j + 1) >= 'A' && words[i].charAt(j + 1) <= 'Z') {
sb2.append(words[i].charAt(j) + "_");
continue;
}
}
}
sb2.append(words[i].charAt(j));
}
words[i] = sb2.toString();
sb.append(words[i] + " ");
}
return sb.toString();
}
输出结果
|