を示すエラーメッセージを取得しています:
somestring.substring(0, 1).toUpperCase() + somestring.substring(1);
あなたの場合は:
String trimmed = newName.trim();
name = trimmed.substring(0, 1).toUpperCase() + trimmed.substring(1);
substring()
は、文字列のある特定の部分を取り、それをキャプチャ(私はname
がすでに初期化されていると仮定しています)。 substring(0, 1)
は、単語の最初の文字を取得し、toUpperCase()
で大文字にします。 substring(1)
は最初の文字の残りの文字列を取り、それを大文字と連結して次の出力を生成します。
へ
"examplestring"
、
"Examplestring"
から、私はまた、残りは小文字であることを余分に確認するためにtoLowerCase()
を利用をお勧めします。最後に、実際に文字列インデックスが存在することを確認するためにtry/catchを実行します。 「フェイルセーフ」をされ、最終的なコード:
String trimmed = newName.trim();
try {
name = trimmed.substring(0, 1).toUpperCase() + trimmed.substring(1).toLowerCase();
} catch(StringIndexOutOfBoundsException e) {
e.printStrackTrace();
System.out.println("String was not at least one character!");
}
trim()
のみ末尾の空白を取り除くので、そのようreplaceAll()
メソッドを使用します:
str.replaceAll("\\s+", "");
は、これは(改行のようなものを含む、すべての空白を置き換える\ n)。これは正規表現(正規表現)を使用してすべての空白にマッチし、何も置き換えません。
try {
name = newName.substring(0, 1).toUpperCase() + newName.substring(1).toLowerCase();
} catch(StringIndexOutOfBoundsException e) {
e.printStrackTrace();
System.out.println("String was not at least one character!");
}
name.replaceAll("\\s+", "");
は、完全なポストを読んでみてください。
TL DR
はここすべての空白を削除し、最初の文字を大文字のコードです。
アプリケーション
public String formatNameTitleCase(String oldName) {
try {
name = oldName.substring(0, 1).toUpperCase() + oldName.substring(1).toLowerCase();
} catch(StringIndexOutOfBoundsException e) {
e.printStrackTrace();
System.out.println("String was not at least one character!");
return "failed";
}
name.replaceAll("\\s+", "");
return name;
}
残念ながら悪いペースト。 – kurt
コードの書式を学ぶ – Li357
publicプール(newName!= null && newName.trim().Length()> 0){ name = formatNameTitleCase(newName.trim()); } else { name = DEFAULT_POOL_NAME; } – kurt