日期:2014-05-20 浏览次数:21075 次
package shi.test;
public class Test
{
public Test()
{
char ch;
String s=null;
StringBuffer str=new StringBuffer();
StringBuffer sb=new StringBuffer("this is a java program");
for(int i=0;i<sb.length();i++)
{
if((ch=sb.charAt(i))==' ')
{
s=String.valueOf(sb.charAt(i+1)).toUpperCase();//把空格后的那个字符转换为大写字母
sb=sb.deleteCharAt(i+1);//删除原字符串中空格后的那个字符
str.append(" "+s);
}
else
{
if(i==0)//判断是不是第一个字母
{
str.append(String.valueOf(sb.charAt(i)).toUpperCase());
}
else
{
str.append(sb.charAt(i));
}
}
}
for(int i=0;i<str.length();i++)
{
System.out.println(str.toString());
}
}
public static void main(String args[])
{
new Test();
}
}
------解决方案--------------------
既然是句子,每个单词间都有空格撒,按空格分成单词数组,再修改各各单词,组成新句子(如果还有其他区分条件类似细分,如逗号):
public class SentenceFilter {
public static void main(String[] args) {
String sentence = "it's new world";
System.out.println(filterSentence(sentence));
}
public static String filterSentence(String sentence) {
String[] wordArr = sentence.split(" ");
StringBuffer newSentence = new StringBuffer();
for(String word : wordArr) {
newSentence.append(word.substring(0, 1).toUpperCase());
if(word.length() > 1) {
newSentence.append(word.substring(1, word.length()));
}
newSentence.append(" ");
}
return newSentence.toString();
}
}
------解决方案--------------------
public static String upCase(String s) {
StringBuffer sb = new StringBuffer(" ").append(s);
char thisChar = ' ';
char lastChar = ' ';
for (int i = 1; i < sb.length(); i++) {
thisChar = sb.charAt(i);
lastChar = sb.charAt(i-1);
if ((i == 0 || lastChar == ' ') && Character.isLetter(thisChar)) {// 条件:// 若是字母且前一个是空格
sb.setCharAt(i, Character.toUpperCase(thisChar));// 变成大写字母
}
}
return sb.toString();
}