/*************************************************************************
* Compilation: javac Capitalize.java
* Execution: java Capitalize < input.txt
*
* Read in a sequence of words from standard input and capitalize each
* one (make first letter uppercase; make rest lowercase).
*
* % java Capitalize
* now is the time for all good
* Now Is The Time For All Good
* to be or not to be that is the question
* To Be Or Not To Be That Is The Question
*
* Remark: replace sequence of whitespace with a single space.
*
*************************************************************************/
public class Capitalize {
public static String capitalize(String s) {
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static void main(String[] args) {
while (!StdIn.isEmpty()) {
String line = StdIn.readLine();
String[] words = line.split("\\s");
for (String s : words) {
StdOut.print(capitalize(s) + " ");
}
StdOut.println();
}
}
}
此外, Spring Framework 中有 org.springframework.util.StringUtils :
StringUtils.capitalize(str);
492
使用StringTokenizer类的示例:
String st = " hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){
st1=a.nextToken();
f=Character.toUpperCase(st1.charAt(0));
fs+=f+ st1.substring(1);
System.out.println(fs);
}
1
Simplest way to do is:
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}
15 回答
用这个:
您可以在java.util包中使用内置函数:
确保字符串不是事先大写的 .
它只需要一行代码就可以了 . if
String A = scanner.nextLine();
然后你需要写这个来显示首字母大写的字符串 .System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
它现在完成了 .
最简单的方法是使用
org.apache.commons.lang.StringUtils
类StringUtils.capitalize(Str);
你走了(希望这能给你一个想法):
如果您只想将名为
input
的字符串的第一个字母大写,并将其余字母留下:现在
output
将拥有你想要的东西 . 在使用之前检查input
至少是一个字符,否则你会得到一个例外 .StringBuilder的解决方案:
..基于以前的答案
StringUtils.capitalize(str)
来自apache commons-lang .
将所有内容添加到一起,最好在字符串的开头修剪额外的空白区域 . 否则,.substring(0,1).toUpperCase将尝试大写空格 .
只是...一个完整的解决方案,我看到它刚刚结束了所有其他人最终发布= P的结果 .
此外, Spring Framework 中有
org.springframework.util.StringUtils
:使用StringTokenizer类的示例: