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.

181
demandé sur Cœur 2011-04-20 09:27:00

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.

481
répondu WhiteFang34 2011-04-20 05:43:22
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.

77
répondu Anther 2015-11-18 20:52:14

Plus Simple est d'utiliser org.apache.commons.lang.StringUtils classe

StringUtils.capitalize(Str);

50
répondu Haseeb 2016-04-07 11:35:10

En outre, il y a org.springframework.util.StringUtils dans Spring Framework :

StringUtils.capitalize(str);
16
répondu Igor Rybak 2017-07-17 20:37:37
6
répondu emanuel07 2017-09-05 04:08:16
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
5
répondu Samet öztoprak 2017-12-24 21:45:42
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);
3
répondu Avantika 2015-06-28 21:23:28

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();
        }
    }

}
2
répondu cMinor 2011-04-20 05:33:07

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);
} 
1
répondu nada 2016-12-16 22:08:00

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.

1
répondu Vismay Hingwala 2017-10-26 19:58:16

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

0
répondu gnB 2017-08-04 19:53:39

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);
0
répondu Jason Bierbrauer 2018-02-08 00:59:17

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);
    }
0
répondu Jeff Padgett 2018-08-28 03:27:10
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);
    }
 }
-1
répondu Bimlendu Kumar 2018-04-25 05:41:25

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.

-3
répondu Maccen Wright 2018-02-08 00:59:56