[英]Force a stringBuilder to an upper case
我想知道是否还有像StringBuilder的toUpperCase这样的东西? 下面是我的代码,我正在尝试用户输入一个短语并将其转换为首字母缩略词。 有人通过建议StringBuilder帮助我,但我无法弄清楚是否有办法使首字母缩写大写。 任何帮助是极大的赞赏。
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
int count = 0;
int MAX = 3;
char c;
//create stringbuilder
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
//get user input for phrase
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
//create an array to split phrase into seperate words.
String[] threeWordsArray = threeWords.split(" ");
//loop through user input and grab first char of each word.
for(String word : threeWordsArray) {
if(count < MAX) {
acronym.append(word.substring(0, 1));
++count;
}//end if
}//end for
System.out.println("The acronym of the three words you entered is: " + acronym);
}//end main
}//end class
只需将大写字符串附加到它:
acronym.append(word.substring(0, 1).toUpperCase())
或者从StringBuilder获取String时将String转换为大写:
System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());
只需将大写字符串附加到StringBuilder即可。
//loop through user input and grab first char of each word.
for(String word : threeWordsArray) {
if(count < MAX) {
acronym.append(word.substring(0, 1).toUpperCase());
++count;
}//end if
}//end for
或者从StringBuilder获取String时大写字符串。
System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());
如果你需要一个库,请看一下Apache Common Lang WordUtils , WordUtils.capitalize(str)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.