文字列の例
one thousand only
two hundred
twenty
seven
文字列の最初の文字を大文字に変更し、他の文字の大文字と小文字を変更しないようにするにはどうすればよいですか?
変更後は次のようになります。
One thousand only
Two hundred
Twenty
Seven
注:これを行うためにapache.commons.lang.WordUtilsを使用したくありません。
文字列の例
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これを使用する前に、あなたの文字が少なくとも1文字であることを確認してください。そうしないと、例外が発生します。
public String capitalizeFirstLetter(String original) {
    if (original == null || original.length() == 0) {
        return original;
    }
    return original.substring(0, 1).toUpperCase() + original.substring(1);
}
ただ...完全なソリューションです。他のすべての人が投稿したもの= Pを組み合わせたようなものだと思います。
return original.length() == 0 ? original : original.substring(0, 1).toUpperCase() + original.substring(1);
                    if length() == 0安全だと言ってそれ""を返すのではなく、安全originalですか?ワンライナーで数文字節約できます。私は、Javaは非常に雑多な言語だと思っているので、長さ0の文字列を使用する他の方法があったとしても、正直に驚かないでしょう。
                    String.toUpperCase(Locale)ロケールはテキストと一致する必要があるため、任意の文字列に使用することはできません。はい、使用する必要がありますが、どちらLocaleを使用するかが必ずしも明確ではありません...
                    最も簡単な方法は、org.apache.commons.lang.StringUtilsクラスを使用することです
StringUtils.capitalize(Str);
capitalizeませんか
                    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);
ここに行きます(これがあなたにアイデアを与えることを願っています):
/*************************************************************************
 *  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();
        }
    }
}StdInてStdOutいるわけではありません。:-)
                    すべてを一緒に追加する場合は、文字列の先頭にある余分な空白を削除することをお勧めします。それ以外の場合、.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);
    }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)を使用できます。あなたが要求したよりも強力です。また、完全に大文字にすることもできます(たとえば、修正"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]));
  }
}これを使って:
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();
}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;
    }受け入れられた回答に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]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)); // nullStringUtilsCommons Lang のクラスは、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>これらの2つのアプローチを詳細に説明する記事を次に示します。
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);
    }
 }