[英]How to capitalize the first letter of word in a string using Java?
示例字符串
one thousand only
two hundred
twenty
seven
如何以大寫字母更改字符串的第一個字符而不更改任何其他字母的大小寫?
更改后應該是:
One thousand only
Two hundred
Twenty
Seven
注意:我不想使用 apache.commons.lang.WordUtils 來做到這一點。
如果您只想將名為input
的字符串的第一個字母大寫,而不要理會其余部分:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
現在output
將有你想要的。 在使用之前檢查您的input
是否至少有一個字符長,否則您將收到異常。
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
只是......一個完整的解決方案,我認為它最終結合了其他人最終發布的內容= P。
最簡單的方法是使用org.apache.commons.lang.StringUtils
類
StringUtils.capitalize(Str);
此外, Spring Framework 中有org.springframework.util.StringUtils
:
StringUtils.capitalize(str);
String sentence = "ToDAY WeAthEr GREat";
public static String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
String newSentence = "";
for (String word : words) {
for (int i = 0; i < word.length(); i++)
newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase():
(i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
}
return newSentence;
}
//Today Weather Great
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);
它的簡單只需要一行代碼。 如果String A = scanner.nextLine();
那么你需要寫這個來顯示第一個字母大寫的字符串。
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
它現在完成了。
給你(希望這給你的想法):
/*************************************************************************
* 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();
}
}
}
使用 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);
}
使用 StringBuilder 的解決方案:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
..基於以前的答案
將所有內容加在一起,最好在字符串開頭修剪多余的空白。 否則, .substring(0,1).toUpperCase 將嘗試大寫空格。
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
我的功能方法。 它在整個段落的whitescape之后將句子中的第一個字符capstilise。
對於僅使用單詞的第一個字符,只需刪除.split(" ")
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
public static String capitalize(String str){
String[] inputWords = str.split(" ");
String outputWords = "";
for (String word : inputWords){
if (!word.isEmpty()){
outputWords = outputWords + " "+StringUtils.capitalize(word);
}
}
return outputWords;
}
2019 年 7 月更新
目前,用於執行此操作的最新庫函數包含在org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils;
StringUtils.capitalize(myString);
如果您使用 Maven,請在 pom.xml 中導入依賴項:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
即使對於“簡單”代碼,我也會使用庫。 問題不是代碼本身,而是已經存在的測試用例,涵蓋了例外情況。 這可能是null
、空字符串、其他語言的字符串。
單詞操作部分已移出 Apache Commons Lang。 它現在被放置在Apache Commons Text 中。 通過https://search.maven.org/artifact/org.apache.commons/commons-text獲取。
您可以使用 Apache Commons Text 中的WordUtils.capitalize(String str) 。 它比你要求的更強大。 它還可以大寫 fulle(例如,修復"oNe tousand only"
)。
由於它適用於完整的文本,因此必須告訴它僅將第一個單詞大寫。
WordUtils.capitalize("one thousand only", new char[0]);
完整的 JUnit 類可以使用以下功能:
package io.github.koppor;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test
void test() {
assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
}
}
如果您只想大寫第一個字母,則可以使用以下代碼
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
實際上,如果在這種情況下避免+
運算符並使用concat()
,您將獲得最佳性能。 它是僅合並 2 個字符串的最佳選擇(盡管對許多字符串不太好)。 在這種情況下,代碼將如下所示:
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
用這個:
char[] chars = {Character.toUpperCase(A.charAt(0)),
Character.toUpperCase(B.charAt(0))};
String a1 = chars[0] + A.substring(1);
String b1 = chars[1] + B.substring(1);
給定input
字符串:
Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
您可以嘗試以下代碼:
public string capitalize(str) {
String[] array = str.split(" ");
String newStr;
for(int i = 0; i < array.length; i++) {
newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
}
return newStr.trim();
}
我想在接受的答案上添加 NULL 檢查和 IndexOutOfBoundsException。
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Java代碼:
class Main {
public static void main(String[] args) {
System.out.println("Capitalize first letter ");
System.out.println("Normal check #1 : ["+ captializeFirstLetter("one thousand only")+"]");
System.out.println("Normal check #2 : ["+ captializeFirstLetter("two hundred")+"]");
System.out.println("Normal check #3 : ["+ captializeFirstLetter("twenty")+"]");
System.out.println("Normal check #4 : ["+ captializeFirstLetter("seven")+"]");
System.out.println("Single letter check : ["+captializeFirstLetter("a")+"]");
System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
System.out.println("Null Check : ["+ captializeFirstLetter(null)+"]");
}
static String captializeFirstLetter(String input){
if(input!=null && input.length() >0){
input = input.substring(0, 1).toUpperCase() + input.substring(1);
}
return input;
}
}
輸出:
Normal check #1 : [One thousand only]
Normal check #2 : [Two hundred]
Normal check #3 : [Twenty]
Normal check #4 : [Seven]
Single letter check : [A]
IndexOutOfBound check : []
Null Check : [null]
無論輸入字符串的值如何,以下內容都會為您提供相同的一致輸出:
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}
substring()
方法public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
現在只需調用capitalize()
方法將字符串的第一個字母轉換為大寫:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
Commons Lang 的StringUtils
類提供了也可用於此目的的capitalize()
方法:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
將以下依賴項添加到您的pom.xml
文件(僅適用於 Maven):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
這里有一篇文章詳細解釋了這兩種方法。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.