Cela peut sembler simple mais il possède beaucoup de bugs
J'ai essayé de cette façon: et il jette une exception p> un autre essai que j'avais été: p> rhis On lance également une exception p> p>
4 Réponses :
/**
* returns the string, the first char lowercase
*
* @param target
* @return
*/
public final static String asLowerCaseFirstChar(final String target) {
if ((target == null) || (target.length() == 0)) {
return target; // You could omit this check and simply live with an
// exception if you like
}
return Character.toLowerCase(target.charAt(0))
+ (target.length() > 1 ? target.substring(1) : "");
}
/**
* returns the string, the first char uppercase
*
* @param target
* @return
*/
public final static String asUpperCaseFirstChar(final String target) {
if ((target == null) || (target.length() == 0)) {
return target; // You could omit this check and simply live with an
// exception if you like
}
return Character.toUpperCase(target.charAt(0))
+ (target.length() > 1 ? target.substring(1) : "");
}
mon problème était si trivial son tout sur NULL String
concernant votre première tentative: p>
static public CharSequence upperFirst(CharSequence s) {
if (s.length() == 0) {
return s;
} else {
return Character.toUpperCase(s.charAt(0))
+ s.subSequence(1, s.length()).toString();
}
}
public static void main(String[] args) {
String[] tests = {
"xyz", "123 abc", "x", ""
};
for (String s : tests) {
System.out.printf("[%s]->[%s]%n", s, upperFirst(s));
}
// [xyz]->[Xyz]
// [123 abc]->[123 abc]
// [x]->[X]
// []->[]
StringBuilder sb = new StringBuilder("blah");
System.out.println(upperFirst(sb));
// prints "Blah"
}
. . . Ou faites-le tout dans un tableau. Voici quelque chose de similaire.
String titleize(String source){
boolean cap = true;
char[] out = source.toCharArray();
int i, len = source.length();
for(i=0; i<len; i++){
if(Character.isWhitespace(out[i])){
cap = true;
continue;
}
if(cap){
out[i] = Character.toUpperCase(out[i]);
cap = false;
}
}
return new String(out);
}
J'aime utiliser cette solution plus simple pour les noms, où TOP est une gamme de noms complets divisés par (""):
for (String line : toUp) {
result = result + Character.toUpperCase(line.charAt(0)) +
line.substring(1).toLowerCase();
}
L'exception que vous obtenez pourrait aider les gens à répondre à cela