串的简单转换

来源:互联网 发布:gcc下载 windows 编辑:程序博客网 时间:2024/06/08 15:27
串的处理在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下: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 dati;
public class dancichuli {
public static void main(String args[]){
danci("A");
}
static void danci(String s){
String str=s;str=str.replaceAll( "(\\s)\\1+","$1");
str=str.replaceAll("([0-9])([a-zA-Z])","$1_$2");
str=str.replaceAll("([a-zA-Z])([0-9])","$1_$2");
String[] words=str.split(" ");
String ntr="";
for(int i=0;i<words.length;i++){
String word=words[i];
if(Character.isLetter(word.charAt(0))){
ntr+=(Character.toUpperCase(word.charAt(0))+word.substring(1)+" ");
}
else
 ntr+=word+" ";
}
System.out.println(ntr);
}
}
原创粉丝点击