如何用java程序使一个英文句子的每个开头字母变成大写?
比如一句话:this is a java program 变成:This Is A Java Program
只要求每个单词的首字母变成大写(或者大写变成小写也可)
谢谢!
------解决方案--------------------------------------------------------
- Java code
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(); }}
------解决方案--------------------------------------------------------
既然是句子,每个单词间都有空格撒,按空格分成单词数组,再修改各各单词,组成新句子(如果还有其他区分条件类似细分,如逗号):
- Java code
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(); }}
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
改了一下10楼的代码:
- Java code
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(); }