题目
变换字符串,使之满足如下要求:
1.将字符串中的多个空格合并为一个空格;
2.将字符串中的每个单词的首字母转换为大写,该单词中的其它字母转换为小写;
3.若字母和数字相邻,则将字母与数字以空格隔开。
例如:
处理前字符串:“nothing23can 13be compared34 with 4 her 99 beauty”
处理后字符串:“Nothing_23_Can 13_Be Compared_34 With 4 Her 99 Beauty”
Java代码实现
public static void StringProcess(String str) {
int len = str.length();
int flag = 0;// 0:前面字符为空格;1:前面字符为数字;2:前面字符为字母
String res = "";
for (int i = 0; i < len; i++) {
char tmp = str.charAt(i);
if (((tmp >= 'A' && tmp <= 'Z') || (tmp >= 'a' && tmp <= 'z'))) {//如果tmp为字母
if (flag == 0) //前一个字符为空格
res += Character.toString(tmp).toUpperCase();
else if (flag == 1) //前一个字符为数字
res += ("_" + Character.toString(tmp).toUpperCase());
else //前一个字符为字母
res += Character.toString(tmp).toLowerCase();
flag = 2;
} else if (tmp == ' ') {//如果tmp为空格(Space)
if (flag != 0)
res += tmp;
flag = 0;
} else {// tmp为数字
if (flag == 2)
res += ("_" + Character.toString(tmp));
else
res += tmp;
flag = 1;
}
}
System.out.println(res);
}
该解决方法有点笨,不过也算是一种解决方案。