簡體   English   中英

如何將Java中的String首字母大寫?

[英]How to capitalize the first letter of a String in Java?

我正在使用 Java 從用戶那里獲取String輸入。 我正在嘗試將此輸入的首字母大寫。

我試過這個:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

這導致了這些編譯器錯誤:

  • 類型不匹配:無法從 InputStreamReader 轉換為 BufferedReader

  • 無法對原始類型 char 調用 toUppercase()

String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"

用你的例子:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    // Actually use the Reader
    String name = br.readLine();
    // Don't mistake String object with a Character object
    String s1 = name.substring(0, 1).toUpperCase();
    String nameCapitalized = s1 + name.substring(1);
    System.out.println(nameCapitalized);
}

將字符串的第一個字母大寫的更短/更快的版本代碼是:

String name  = "stackoverflow"; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

name的值為"Stackoverflow"

使用 Apache 的公共庫。 將您的大腦從這些東西中解放出來,避免空指針和索引越界異常

步驟1:

通過將其放入build.gradle依賴項中導入 apache 的公共語言庫

compile 'org.apache.commons:commons-lang3:3.6'

第2步:

如果你確定你的字符串都是小寫的,或者你只需​​要初始化第一個字母,直接調用

StringUtils.capitalize(yourString);

如果您想確保只有第一個字母大寫,例如對enum執行此操作,請先調用toLowerCase()並記住,如果輸入字符串為空,它將拋出NullPointerException

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

以下是 apache 提供的更多示例。 這是免費的

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

筆記:

WordUtils也包含在此庫中,但已棄用。 不要使用它。

爪哇:

只是一個用於大寫每個字符串的輔助方法。

public static String capitalize(String str)
{
    if(str == null || str.length()<=1) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

之后只需調用str = capitalize(str)


科特林:

str.capitalize()

如果您使用SPRING

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

實現 org/springframework/util/StringUtils.java#L535-L555

參考: javadoc-api/org/springframework/util/StringUtils.html#capitalize


注意:如果您已經有 Apache Common Lang 依賴項,那么請考慮使用他們的 StringUtils.capitalize 作為其他答案的建議。

你想要做的可能是這樣的:

s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

(將第一個字符轉換為大寫並添加原始字符串的其余部分)

此外,您創建了一個輸入流閱讀器,但從不讀取任何行。 因此name將始終為null

這應該有效:

BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

以下解決方案將起作用。

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

您不能在原始 char 上使用 toUpperCase() ,但您可以先將整個字符串設為大寫,然后取第一個字符,然后附加到子字符串,如上所示。

使用此實用方法獲取所有首字母大寫。

String captializeAllFirstLetter(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);

    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }

    return new String(array);
}

將字符串設置為小寫,然后將第一個字母設置為大寫,如下所示:

    userName = userName.toLowerCase();

然后將第一個字母大寫:

    userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

substring 只是得到一個更大的字符串,然后我們將它們組合在一起。

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

它將工作 101%

public class UpperCase {

    public static void main(String [] args) {

        String name;

        System.out.print("INPUT: ");
        Scanner scan = new Scanner(System.in);
        name  = scan.next();

        String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
        System.out.println("OUTPUT: " + upperCase); 

    }

}

這是我關於所有可能選項的主題的詳細文章在Android中將字符串的首字母大寫

Java中字符串首字母大寫的方法

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

KOTLIN 中字符串首字母大寫的方法

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

也是最短的:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

為我工作。

在 Android Studio 中

將此依賴項添加到您的build.gradle (Module: app)

dependencies {
    ...
    compile 'org.apache.commons:commons-lang3:3.1'
    ...
}

現在你可以使用

String string = "STRING WITH ALL CAPPS AND SPACES";

string = string.toLowerCase(); // Make all lowercase if you have caps

someTextView.setText(WordUtils.capitalize(string));

WordUtils.capitalizeFully()怎么樣?

import org.apache.commons.lang3.text.WordUtils;

public class Main {

    public static void main(String[] args) {

        final String str1 = "HELLO WORLD";
        System.out.println(capitalizeFirstLetter(str1)); // output: Hello World

        final String str2 = "Hello WORLD";
        System.out.println(capitalizeFirstLetter(str2)); // output: Hello World

        final String str3 = "hello world";
        System.out.println(capitalizeFirstLetter(str3)); // output: Hello World

        final String str4 = "heLLo wORld";
        System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
    }

    private static String capitalizeFirstLetter(String str) {
        return WordUtils.capitalizeFully(str);
    }
}

您可以使用substring()來執行此操作。

但是有兩種不同的情況:

情況1

如果您要大寫的String是人類可讀的,您還應該指定默認語言環境:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

案例2

如果您要大寫的String是機器可讀的,請避免使用Locale.getDefault()因為返回的字符串在不同區域之間會不一致,並且在這種情況下始終指定相同的語言環境(例如, toUpperCase(Locale.ENGLISH) . toUpperCase(Locale.ENGLISH) )。 這將確保您用於內部處理的字符串是一致的,這將幫助您避免難以發現的錯誤。

注意:您不必為toLowerCase()指定Locale.getDefault() ) ,因為這是自動完成的。

你也可以試試這個:

 String s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

這比使用子字符串更好(優化)。 (但不要擔心小字符串)

要獲得首字母大寫和其他小寫字母,您可以使用以下代碼。 我已經通過子字符串函數完成了。

String currentGender="mAlE";
    currentGender=currentGender.substring(0,1).toUpperCase()+currentGender.substring(1).toLowerCase();

這里 substring(0,1).toUpperCase() 將首字母轉換為大寫, substring(1).toLowercase() 將所有剩余的字母轉換為小寫。

輸出:

男性

試試這個

這個方法的作用是,考慮單詞“hello world”這個方法把它變成“Hello World”,每個單詞的開頭都大寫。

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }
["

當前的答案要么不正確,要么使這個簡單的任務過於復雜。 在做了一些研究之后,我提出了兩種方法

1.String的substring()方法

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

例子:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons 朗

Apache Commons Lang 庫為此目的提供了StringUtils類:

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文件中:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

簡單的解決方案! 不需要任何外部庫,它可以處理空字符串或一個字母字符串。

private String capitalizeFirstLetter(@NonNull  String str){
        return str.length() == 0 ? str
                : str.length() == 1 ? str.toUpperCase()
                : str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}

這將起作用

char[] array = value.toCharArray();

array[0] = Character.toUpperCase(array[0]);

String result = new String(array);

您可以使用以下代碼:

public static void main(String[] args) {

    capitalizeFirstLetter("java");
    capitalizeFirstLetter("java developer");
}

public static void capitalizeFirstLetter(String text) {

    StringBuilder str = new StringBuilder();

    String[] tokens = text.split("\\s");// Can be space,comma or hyphen

    for (String token : tokens) {
        str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
    }
    str.toString().trim(); // Trim trailing space

    System.out.println(str);

}

這只是為了告訴你,你並沒有那么錯。

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

注意:這根本不是最好的方法。 這只是為了向 OP 展示它也可以使用charAt()來完成。 ;)

使用commons.lang.StringUtils最好的答案是:

public static String capitalize(String str) {  
    int strLen;  
    return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;  
}

我覺得它很棒,因為它用 StringBuffer 包裝了字符串。 您可以根據需要操作 StringBuffer,盡管使用相同的實例。

如果輸入是大寫,則使用以下:

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

如果輸入是小寫,則使用以下:

str.substring(0, 1).toUpperCase() + str.substring(1);

看看 ACL WordUtils。

WordUtils.capitalize("你的字符串") == "你的字符串"

如何將字符串中單詞的每個首字母大寫?

public static String capitalizer(final String texto) {

    // split words
    String[] palavras = texto.split(" ");
    StringBuilder sb = new StringBuilder();

    // list of word exceptions
    List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));

    for (String palavra : palavras) {

        if (excessoes.contains(palavra.toLowerCase()))
            sb.append(palavra.toLowerCase()).append(" ");
        else
            sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
    }
    return sb.toString().trim();
}

您可以使用以下代碼:

public static String capitalizeString(String string) {

    if (string == null || string.trim().isEmpty()) {
        return string;
    }
    char c[] = string.trim().toLowerCase().toCharArray();
    c[0] = Character.toUpperCase(c[0]);

    return new String(c);

}

使用 JUnit 進行示例測試:

@Test
public void capitalizeStringUpperCaseTest() {

    String string = "HELLO WORLD  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}

@Test
public void capitalizeStringLowerCaseTest() {

    String string = "hello world  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}

您可以使用子字符串進行簡單的黑客攻擊;)。

String name;
    
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());

System.out.println(s1));
System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

PS = a 是一個字符串。

又一個例子,如何使用戶輸入的第一個字母大寫:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
        IntStream.of(string.codePointAt(0))
                .map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));

因為您首先從原始字符串中獲取 Char 。 您不能在 char 上使用 String 屬性,因此只需先使用 to upper 然后使用 charAt

String s1 = name.toUppercase().charAt(0);

許多答案非常有幫助,因此我使用它們創建了一種將任何字符串轉換為標題的方法(第一個字符大寫):

static String toTitle (String s) {
      String s1 = s.substring(0,1).toUpperCase();
      String sTitle = s1 + s.substring(1);
      return sTitle;
 }

由於與字符串長度相關的情況很少,因此只是重新編寫了 Jorgesys 代碼並添加了一些檢查 在我的情況下,不要進行空參考檢查。

 public static String capitalizeFirstLetter(@NonNull String customText){
        int count = customText.length();
        if (count == 0) {
            return customText;
        }
        if (count == 1) {
            return customText.toUpperCase();
        }
        return customText.substring(0, 1).toUpperCase() + customText.substring(1).toLowerCase();
    }

要將字符串中每個單詞的第一個字符大寫,

首先,您需要使用下面的拆分方法獲取該字符串的每個單詞&對於該拆分字符串,其中有任何空格,並將每個單詞存儲在一個數組中。 然后創建一個空字符串。 之后使用 substring() 方法獲取相應單詞的第一個字符和剩余字符並將它們存儲在兩個不同的變量中。

然后通過使用 toUpperCase() 方法將第一個字符大寫並將如下剩余字符添加到該空字符串中。

public class Test {  
     public static void main(String[] args)
     {
         String str= "my name is khan";        // string
         String words[]=str.split("\\s");      // split each words of above string
         String capitalizedWord = "";         // create an empty string

         for(String w:words)
         {  
              String first = w.substring(0,1);    // get first character of each word
              String f_after = w.substring(1);    // get remaining character of corresponding word
              capitalizedWord += first.toUpperCase() + f_after+ " ";  // capitalize first character and add the remaining to the empty string and continue
         }
         System.out.println(capitalizedWord);    // print the result
     }
}

我發布的代碼將從字符串中刪除下划線(_)符號和多余的空格,並且它將大寫字符串中每個新單詞的首字母

private String capitalize(String txt){ 
  List<String> finalTxt=new ArrayList<>();

  if(txt.contains("_")){
       txt=txt.replace("_"," ");
  }

  if(txt.contains(" ") && txt.length()>1){
       String[] tSS=txt.split(" ");
       for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }  
  }

  if(finalTxt.size()>0){
       txt="";
       for(String s:finalTxt){ txt+=s+" "; }
  }

  if(txt.endsWith(" ") && txt.length()>1){
       txt=txt.substring(0, (txt.length()-1));
       return txt;
  }

  txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
  return txt;
}

答案之一是 95% 正確,但在我的 unitTest 中失敗了 @Ameen Maheen 的解決方案幾乎是完美的。 除了在輸入轉換為字符串數組之前,您必須修剪輸入。 所以完美的一個:

private String convertStringToName(String name) {
        name = name.trim();
        String[] words = name.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return sb.toString();
    }

給出的答案僅用於將一個單詞的第一個字母大寫。 使用以下代碼將整個字符串大寫。

public static void main(String[] args) {
    String str = "this is a random string";
    StringBuilder capitalizedString = new StringBuilder();
    String[] splited = str.trim().split("\\s+");

    for (String string : splited) {         
        String s1 = string.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + string.substring(1);

        capitalizedString.append(nameCapitalized);
        capitalizedString.append(" ");
    }
    System.out.println(capitalizedString.toString().trim());
}

輸出: This Is A Random String

使用替換方法。

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());

以下示例還在特殊字符后大寫單詞,例如 [/-]

  public static String capitalize(String text) {
    char[] stringArray = text.trim().toCharArray();
    boolean wordStarted = false;
    for( int i = 0; i < stringArray.length; i++) {
      char ch = stringArray[i];
      if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '\'') {
        if( !wordStarted ) {
          stringArray[i] = Character.toUpperCase(stringArray[i]);
          wordStarted = true;
        } 
      } else {
        wordStarted = false;
      }
    }
    return new String(stringArray);
  }

Example:
capitalize("that's a beautiful/wonderful life we have.We really-do")

Output:
That's A Beautiful/Wonderful Life We Have.We Really-Do

謝謝我已經閱讀了一些評論,我帶來了以下內容

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

我希望它有助於祝你好運

Ameen Mahheen 的答案很好,但是如果我們有一些帶有雙空格的字符串,比如“hello world”,那么 sb.append 會得到 IndexOutOfBounds 異常。 正確的做法是在此行之前進行測試,執行以下操作:

private String capitalizer(String word){
        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                if (words[i].length() > 0) sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();
    }

你可以試試這個

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

您可以使用 WordUtils 類。

假設您的字符串是“當前地址”,然后使用

**** 強文本Wordutils.capitaliz(String); 輸出:當前地址

參考: http ://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

class CapitalizeWords
{
    public static void main(String[] args) 
    {
        String input ="welcome to kashmiri geeks...";

        System.out.println(input);

        String[] str = input.split(" ");

        for(int i=0; i< str.length; i++)
        {
            str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
        }

        for(int i=0;i<str.length;i++)
        {
            System.out.print(str[i]+" ");
        }


    }
}
String s = "first second third fourth";

        int j = 0;
        for (int i = 0; i < s.length(); i++) {

            if ((s.substring(j, i).endsWith(" "))) {

                String s2 = s.substring(j, i);
                System.out.println(Character.toUpperCase(s.charAt(j))+s2.substring(1));
                j = i;
            }
        }
        System.out.println(Character.toUpperCase(s.charAt(j))+s.substring(j+1));

一種方法。

String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
    return "";
}

char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;

這種方法的缺點是,如果 inputString 很長,您將擁有三個這樣長度的對象。 和你一樣

String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;

甚至

//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();

此代碼將文本中的每個單詞大寫!

public String capitalizeText(String name) {
    String[] s = name.trim().toLowerCase().split("\\s+");
    name = "";
    for (String i : s){
        if(i.equals("")) return name; // or return anything you want
        name+= i.substring(0, 1).toUpperCase() + i.substring(1) + " "; // uppercase first char in words
    }
    return name.trim();
}
import java.util.*;
public class Program
{
    public static void main(String[] args) 
      {
        Scanner sc=new Scanner(System.in);
        String s1=sc.nextLine();
        String[] s2=s1.split(" ");//***split text into words***
        ArrayList<String> l = new ArrayList<String>();//***list***
        for(String w: s2)
        l.add(w.substring(0,1).toUpperCase()+w.substring(1)); 
        //***converting 1st letter to capital and adding to list***
        StringBuilder sb = new StringBuilder();//***i used StringBuilder to convert words to text*** 
        for (String s : l)
          {
             sb.append(s);
             sb.append(" ");
          }
      System.out.println(sb.toString());//***to print output***
      }
}

我已經使用 split 函數將字符串拆分為單詞,然后我再次使用 list 來獲取該單詞中的第一個字母大寫,然后我使用 string builder 以字符串格式打印輸出,其中包含空格

為了將輸入字符串的第一個字母大寫,我們首先在空間上拆分字符串,然后使用map提供的集合轉換過程

<T, R> Array<out T>.map(

   transform: (T) -> R

): List<R>

要轉換,每個拆分字符串先小寫,然后大寫第一個字母。 此映射轉換將返回一個需要使用joinToString函數轉換為字符串的列表。

科特林

fun main() {
    
    /*
     * Program that first convert all uper case into lower case then 
     * convert fist letter into uppercase
     */
    
    val str = "aLi AzAZ alam"
    val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
    println(calStr.joinToString(separator = " "))
}

輸出

上述代碼的輸出

這是我這邊的解決方案,檢查所有條件。

   import java.util.Objects;

public class CapitalizeFirstCharacter {

    public static void main(String[] args) {

        System.out.println(capitailzeFirstCharacterOfString("jwala")); //supply input string here
    }

    private static String capitailzeFirstCharacterOfString(String strToCapitalize) {

        if (Objects.nonNull(strToCapitalize) && !strToCapitalize.isEmpty()) {
            return strToCapitalize.substring(0, 1).toUpperCase() + strToCapitalize.substring(1);
        } else {
            return "Null or Empty value of string supplied";

        }

    }

}
  • 字符char不能存儲在String中。
  • charString不能連接。
  • String.valueOf()用於將char轉換為String

Input

india

Code

String name = "india";
char s1 = name.charAt(0).toUppercase()); // output: 'I'
System.out.println(String.valueOf(s1) + name.substring(1)); // output: "I"+ "ndia";

Output

India

'首先你需要這樣做--->

//enter here your string values
String output = str.substring(0, 1).toUpperCase() + str.substring(1);

Output will in this way --->
Enter here your string values

為避免異常(IndexOutOfBoundsException 或 NullPointerException 將 substring(0, 1) 用於空字符串或 null 字符串時),您可以使用正則表達式 ("^.")(自 Java 9 起):

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
        String name = reader.readLine();

        name = Pattern.compile("^.")    // regex for the first character of a string
                .matcher(name)
                .replaceFirst(matchResult -> matchResult.group().toUpperCase());

        System.out.println(name);
    } catch(IOException ignore) {}

那些搜索的人在這里將名字的第一個字母大寫..

public static String capitaliseName(String name) {
    String collect[] = name.split(" ");
    String returnName = "";
    for (int i = 0; i < collect.length; i++) {
        collect[i] = collect[i].trim().toLowerCase();
        if (collect[i].isEmpty() == false) {
            returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
        }
    }
    return returnName.trim();
}

用法:大寫名稱(“saurav khan”);

輸出:索拉夫汗

  1. 如果您只想大寫第一個字母,請使用以下代碼:

     fun capitalizeFirstLetter(str: String): String { return when { str.isEmpty() -> str str.length == 1 -> str.uppercase(Locale.getDefault()) else -> str.substring(0, 1) .uppercase(Locale.getDefault()) + str.substring(1) .lowercase(Locale.getDefault()) }

    }

  2. 如果要將句子中單詞的每個首字母大寫,請使用以下代碼:

     fun capitalizeEveryFirstLetterOfWordInSentence(str: String): String { return when { str.isEmpty() -> str str.length == 1 -> str.uppercase(Locale.getDefault()) else -> str .lowercase(Locale.getDefault()) .split(" ") .joinToString(" ") { it -> it.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } }.trimEnd() }}

3.然后,像這樣簡單地調用函數並傳遞值:

capitalizeFirstLetter("your String")
capitalizeEveryFirstLetterOfWordInSentence("your String")

試試這個,它對我有用。

public static String capitalizeName(String name) {
    String fullName = "";
    String names[] = name.split(" ");
    for (String n: names) {
        fullName = fullName + n.substring(0, 1).toUpperCase() + n.toLowerCase().substring(1, n.length()) + " ";
    }
    return fullName;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM