Comment capitaliser la première lettre de mot dans une chaîne en utilisant Java?
Exemple de chaînes
one thousand only
two hundred
twenty
seven
Comment changer le premier caractère d'une chaîne en majuscule et ne pas changer la casse des autres lettres?
Après le changement, il devrait être:
One thousand only
Two hundred
Twenty
Seven
Note: Je ne veux pas utiliser l'apache.commun.lang.WordUtils pour le faire.
15 réponses
Si vous souhaitez uniquement mettre en majuscule la première lettre d'une chaîne nommée input
et laisser le reste seul:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Maintenant {[2] } aura ce que vous voulez. Vérifiez que votre input
contient au moins un caractère bien avant de l'utiliser, sinon vous obtiendrez une exception.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
Juste... une solution complète, je vois qu'elle a fini par combiner ce que tout le monde a fini par poster =P.
Plus Simple est d'utiliser org.apache.commons.lang.StringUtils
classe
StringUtils.capitalize(Str);
En outre, il y a org.springframework.util.StringUtils
dans Spring Framework :
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);
Voilà (j'espère que cela vous donnera l'idée):
/*************************************************************************
* 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();
}
}
}
Exemple utilisant la classe 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);
}
Son simple code d'une seule ligne est nécessaire pour cela.
si String A = scanner.nextLine();
ensuite, vous devez écrire ceci pour afficher la chaîne avec cette première lettre en majuscule.
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
Et c'est fait maintenant.
Solution avec StringBuilder:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
.. basé sur les réponses précédentes
Utilisez ceci:
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);
En ajoutant tout ensemble, c'est une bonne idée de couper pour un espace blanc supplémentaire au début de la chaîne. Autrement, .sous-chaîne (0,1).toUpperCase va essayer de capitaliser un espace blanc.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(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);
}
}
Vous pouvez simplement utiliser une fonction intégrée dans java.paquet util:
>> import java.util.*;
>> System.out.println(capitalize(input));
Assurez-vous que les chaînes ne sont pas capitalisées avant la main.