gpt4 book ai didi

java - 强制 stringBuilder 为大写

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:08:32 24 4
gpt4 key购买 nike

我想知道是否可以为 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 获取字符串时将字符串转为大写:

System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());

关于java - 强制 stringBuilder 为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31064827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com