java - poner - Cómo capitalizar el primer carácter de cada palabra en una cadena
primera letra de cada palabra en mayuscula mysql (30)
Desde Java 9+
puedes usar String::replceAll
como este:
public static void upperCaseAllFirstCharacter(String text) {
String regex = "//b(.)(.*?)//b";
String result = Pattern.compile(regex).matcher(text).replaceAll(
matche -> matche.group(1).toUpperCase() + matche.group(2)
);
System.out.println(result);
}
Ejemplo:
upperCaseAllFirstCharacter("hello this is Just a test");
Salidas
Hello This Is Just A Test
¿Existe una función integrada en Java que capitaliza el primer carácter de cada palabra en una cadena y no afecta a las otras?
Ejemplos:
-
Jon Skeet
->Jon Skeet
-
miles o''Brien
->Miles O''Brien
(B sigue siendo la capital, esto descarta el caso del título) -
old mcdonald
->old mcdonald
*
* (El Old McDonald
también se encontraría, pero no espero que sea TAN inteligente).
Un vistazo rápido a la documentación de la cadena Java revela solo a toUpperCase()
y toLowerCase()
, que por supuesto no proporcionan el comportamiento deseado. Naturalmente, los resultados de Google están dominados por esas dos funciones. Parece una rueda que ya debe haber sido inventada, por lo que no podía hacer daño preguntar, así que puedo usarla en el futuro.
Éste funciona para el caso del apellido ...
Con diferentes tipos de separadores, y mantiene el mismo separador:
Jean-Frederic -> Jean-Frederic
Jean Frederic -> Jean Frederic
El código funciona con el lado del cliente GWT.
public static String capitalize (String givenString) {
String Separateur = " ,.-;";
StringBuffer sb = new StringBuffer();
boolean ToCap = true;
for (int i = 0; i < givenString.length(); i++) {
if (ToCap)
sb.append(Character.toUpperCase(givenString.charAt(i)));
else
sb.append(Character.toLowerCase(givenString.charAt(i)));
if (Separateur.indexOf(givenString.charAt(i)) >=0)
ToCap = true;
else
ToCap = false;
}
return sb.toString().trim();
}
Aquí está mi solución.
Me encontré con este problema esta noche y decidí buscarlo. Encontré una respuesta de Neelam Singh que casi estaba allí, así que decidí solucionar el problema (se rompió en cadenas vacías) y causé un fallo en el sistema.
El método que está buscando se llama capString(String s)
continuación. Convierte "Son solo las 5 am aquí" en "Es solo las 5 am aquí".
El código está bastante bien comentado, así que disfruta.
package com.lincolnwdaniel.interactivestory.model;
public class StringS {
/**
* @param s is a string of any length, ideally only one word
* @return a capitalized string.
* only the first letter of the string is made to uppercase
*/
public static String capSingleWord(String s) {
if(s.isEmpty() || s.length()<2) {
return Character.toUpperCase(s.charAt(0))+"";
}
else {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
/**
*
* @param s is a string of any length
* @return a title cased string.
* All first letter of each word is made to uppercase
*/
public static String capString(String s) {
// Check if the string is empty, if it is, return it immediately
if(s.isEmpty()){
return s;
}
// Split string on space and create array of words
String[] arr = s.split(" ");
// Create a string buffer to hold the new capitalized string
StringBuffer sb = new StringBuffer();
// Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
// If it is, return the original string immediately
if( arr.length < 1 ){
return s;
}
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
}
Aquí hay una función simple.
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result += Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
Decidí agregar una solución más para poner mayúsculas en una cadena:
- las palabras se definen aquí como caracteres de letras o dígitos adyacentes;
- También se proporcionan pares sustitutos;
- el código ha sido optimizado para el rendimiento; y
- Todavía es compacto.
Función:
public static String capitalize(String string) {
final int sl = string.length();
final StringBuilder sb = new StringBuilder(sl);
boolean lod = false;
for(int s = 0; s < sl; s++) {
final int cp = string.codePointAt(s);
sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
lod = Character.isLetterOrDigit(cp);
if(!Character.isBmpCodePoint(cp)) s++;
}
return sb.toString();
}
Ejemplo de llamada:
System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: 𐐪𐐪."));
Resultado:
An À La Carte String. Surrogate Pairs: 𐐂𐐪.
El siguiente método convierte todas las letras en mayúsculas / minúsculas, dependiendo de su posición cerca de un espacio u otros caracteres especiales.
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]==''.'' || chars[i]==''/''') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
Esta es solo otra forma de hacerlo:
private String capitalize(String line)
{
StringTokenizer token =new StringTokenizer(line);
String CapLine="";
while(token.hasMoreTokens())
{
String tok = token.nextToken().toString();
CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";
}
return CapLine.substring(0,CapLine.length()-1);
}
Esto podría ser útil si necesita capitalizar títulos. Capitaliza cada subcadena delimitada por " "
, excepto por cadenas específicas como "a"
o "the"
. Aún no lo he corrido porque es tarde, aunque debería estar bien. Utiliza Apache Commons StringUtils.join()
en un punto. Puedes sustituirlo por un simple bucle si lo deseas.
private static String capitalize(String string) {
if (string == null) return null;
String[] wordArray = string.split(" "); // Split string to analyze word by word.
int i = 0;
lowercase:
for (String word : wordArray) {
if (word != wordArray[0]) { // First word always in capital
String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
for (String word2 : lowercaseWords) {
if (word.equals(word2)) {
wordArray[i] = word;
i++;
continue lowercase;
}
}
}
char[] characterArray = word.toCharArray();
characterArray[0] = Character.toTitleCase(characterArray[0]);
wordArray[i] = new String(characterArray);
i++;
}
return StringUtils.join(wordArray, " "); // Re-join string
}
Estoy usando la siguiente función. Creo que es más rápido en el rendimiento.
public static String capitalize(String text){
String c = (text != null)? text.trim() : "";
String[] words = c.split(" ");
String result = "";
for(String w : words){
result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
}
return result.trim();
}
Hay muchas maneras de convertir la primera letra de la primera palabra en mayúscula. Tengo una idea. Es muy sencillo:
public String capitalize(String str){
/* The first thing we do is remove whitespace from string */
String c = str.replaceAll("//s+", " ");
String s = c.trim();
String l = "";
for(int i = 0; i < s.length(); i++){
if(i == 0){ /* Uppercase the first letter in strings */
l += s.toUpperCase().charAt(i);
i++; /* To i = i + 1 because we don''t need to add
value i = 0 into string l */
}
l += s.charAt(i);
if(s.charAt(i) == 32){ /* If we meet whitespace (32 in ASCII Code is whitespace) */
l += s.toUpperCase().charAt(i+1); /* Uppercase the letter after whitespace */
i++; /* Yo i = i + 1 because we don''t need to add
value whitespace into string l */
}
}
return l;
}
He escrito una pequeña clase para capitalizar todas las palabras en una cadena.
multiple delimiters
opcionales, cada uno con su comportamiento (capitalizar antes, después o ambos, para manejar casos como O''Brian
);
Locale
opcional;
No rompas con los Surrogate Pairs
.
Salida:
==================================== SIMPLE USAGE ==================================== Source: cApItAlIzE this string after WHITE SPACES Output: Capitalize This String After White Spaces ==================================== SINGLE CUSTOM-DELIMITER USAGE ==================================== Source: capitalize this string ONLY before''and''''after''''''APEX Output: Capitalize this string only beforE''AnD''''AfteR''''''Apex ==================================== MULTIPLE CUSTOM-DELIMITER USAGE ==================================== Source: capitalize this string AFTER SPACES, BEFORE''APEX, and #AFTER AND BEFORE# NUMBER SIGN (#) Output: Capitalize This String After Spaces, BeforE''apex, And #After And BeforE# Number Sign (#) ==================================== SIMPLE USAGE WITH CUSTOM LOCALE ==================================== Source: Uniforming the first and last vowels (different kind of ''i''s) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR) Output: Uniforming The First And Last Vowels (different Kind Of ''i''s) Of The Turkish Word D[i]yarbak[i]r (diyarbakir) ==================================== SIMPLE USAGE WITH A SURROGATE PAIR ==================================== Source: ab 𐐂c de à Output: Ab 𐐪c De À
Nota: la primera letra siempre estará en mayúscula (edite la fuente si no quiere eso).
Por favor, comparte tus comentarios y ayúdame a encontrar errores o mejorar el código ...
Código:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class WordsCapitalizer {
public static String capitalizeEveryWord(String source) {
return capitalizeEveryWord(source,null,null);
}
public static String capitalizeEveryWord(String source, Locale locale) {
return capitalizeEveryWord(source,null,locale);
}
public static String capitalizeEveryWord(String source, List<Delimiter> delimiters, Locale locale) {
char[] chars;
if (delimiters == null || delimiters.size() == 0)
delimiters = getDefaultDelimiters();
// If Locale specified, i18n toLowerCase is executed, to handle specific behaviors (eg. Turkish dotted and dotless ''i'')
if (locale!=null)
chars = source.toLowerCase(locale).toCharArray();
else
chars = source.toLowerCase().toCharArray();
// First charachter ALWAYS capitalized, if it is a Letter.
if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){
chars[0] = Character.toUpperCase(chars[0]);
}
for (int i = 0; i < chars.length; i++) {
if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
// Current char is not a Letter; gonna check if it is a delimitrer.
for (Delimiter delimiter : delimiters){
if (delimiter.getDelimiter()==chars[i]){
// Delimiter found, applying rules...
if (delimiter.capitalizeBefore() && i>0
&& Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
{ // previous character is a Letter and I have to capitalize it
chars[i-1] = Character.toUpperCase(chars[i-1]);
}
if (delimiter.capitalizeAfter() && i<chars.length-1
&& Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
{ // next character is a Letter and I have to capitalize it
chars[i+1] = Character.toUpperCase(chars[i+1]);
}
break;
}
}
}
}
return String.valueOf(chars);
}
private static boolean isSurrogate(char chr){
// Check if the current character is part of an UTF-16 Surrogate Pair.
// Note: not validating the pair, just used to bypass (any found part of) it.
return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
}
private static List<Delimiter> getDefaultDelimiters(){
// If no delimiter specified, "Capitalize after space" rule is set by default.
List<Delimiter> delimiters = new ArrayList<Delimiter>();
delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, '' ''));
return delimiters;
}
public static class Delimiter {
private Behavior behavior;
private char delimiter;
public Delimiter(Behavior behavior, char delimiter) {
super();
this.behavior = behavior;
this.delimiter = delimiter;
}
public boolean capitalizeBefore(){
return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public boolean capitalizeAfter(){
return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public char getDelimiter() {
return delimiter;
}
}
public static enum Behavior {
CAPITALIZE_AFTER_MARKER(0),
CAPITALIZE_BEFORE_MARKER(1),
CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);
private int value;
private Behavior(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Hice una solución en Java 8 que es IMHO más legible.
public String firstLetterCapitalWithSingleSpace(final String words) {
return Stream.of(words.trim().split("//s"))
.filter(word -> word.length() > 0)
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
El resumen de esta solución se puede encontrar aquí: https://gist.github.com/Hylke1982/166a792313c5e2df9d31
La forma corta y precisa es la siguiente:
String name = "test";
name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
-------------------- Output -------------------- Test T empty --------------------
Funciona sin error si intenta cambiar el valor del nombre a los tres valores. Error libre.
Método reutilizable para intiCap:
public class YarlagaddaSireeshTest{
public static void main(String[] args) {
String FinalStringIs = "";
String testNames = "sireesh yarlagadda test";
String[] name = testNames.split("//s");
for(String nameIs :name){
FinalStringIs += getIntiCapString(nameIs) + ",";
}
System.out.println("Final Result "+ FinalStringIs);
}
public static String getIntiCapString(String param) {
if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}
else {
return "";
}
}
}
Para aquellos de ustedes que usan Velocity en su MVC, pueden usar el método capitalizeFirstLetter()
de la clase StringUtils .
Prueba esta manera muy simple
example givenString = "ram es buen chico"
public static String toTitleCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
La salida será: Ram Is Good Boy
Si prefieres la guayaba ...
String myString = ...;
String capWords = Joiner.on('' '').join(Iterables.transform(Splitter.on('' '').omitEmptyStrings().split(myString), new Function<String, String>() {
public String apply(String input) {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
}));
Si solo te preocupa que la primera letra de la primera palabra esté en mayúscula:
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
Usar org.apache.commons.lang.StringUtils
hace muy simple.
capitalizeStr = StringUtils.capitalize(str);
Use el método Dividir para dividir su cadena en palabras, luego use las funciones de cadena incorporadas para poner en mayúscula cada palabra y luego adjuntarlas.
Pseudo-código (ish)
string = "the sentence you want to apply caps to";
words = string.split(" ")
string = ""
for(String w: words)
//This line is an easy way to capitalize a word
word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())
string += word
Al final, la cadena se ve algo así como "La oración a la que quieres aplicar mayúsculas"
Utilizar:
String text = "jon skeet, miles o''brien, old mcdonald";
Pattern pattern = Pattern.compile("//b([a-z])([//w]*)");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
}
String capitalized = matcher.appendTail(buffer).toString();
System.out.println(capitalized);
WordUtils.capitalize(str)
(de apache commons-text )
(Nota: si necesitas "fOO BAr"
para convertirte en "Foo Bar"
, usa capitalizeFully(..)
lugar)
Con este sencillo código :
String example="hello";
example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());
System.out.println(example);
Resultado: Hola
package com.test;
/**
* @author Prasanth Pillai
* @date 01-Feb-2012
* @description : Below is the test class details
*
* inputs a String from a user. Expect the String to contain spaces and alphanumeric characters only.
* capitalizes all first letters of the words in the given String.
* preserves all other characters (including spaces) in the String.
* displays the result to the user.
*
* Approach : I have followed a simple approach. However there are many string utilities available
* for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException{
System.out.println("Input String :/n");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String inputString = in.readLine();
int length = inputString.length();
StringBuffer newStr = new StringBuffer(0);
int i = 0;
int k = 0;
/* This is a simple approach
* step 1: scan through the input string
* step 2: capitalize the first letter of each word in string
* The integer k, is used as a value to determine whether the
* letter is the first letter in each word in the string.
*/
while( i < length){
if (Character.isLetter(inputString.charAt(i))){
if ( k == 0){
newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
k = 2;
}//this else loop is to avoid repeatation of the first letter in output string
else {
newStr = newStr.append(inputString.charAt(i));
}
} // for the letters which are not first letter, simply append to the output string.
else {
newStr = newStr.append(inputString.charAt(i));
k=0;
}
i+=1;
}
System.out.println("new String ->"+newStr);
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence : ");
try
{
String str = br.readLine();
char[] str1 = new char[str.length()];
for(int i=0; i<str.length(); i++)
{
str1[i] = Character.toLowerCase(str.charAt(i));
}
str1[0] = Character.toUpperCase(str1[0]);
for(int i=0;i<str.length();i++)
{
if(str1[i] == '' '')
{
str1[i+1] = Character.toUpperCase(str1[i+1]);
}
System.out.print(str1[i]);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
String s="hi dude i want apple";
s = s.replaceAll("//s+"," ");
String[] split = s.split(" ");
s="";
for (int i = 0; i < split.length; i++) {
split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
s+=split[i]+" ";
System.out.println(split[i]);
}
System.out.println(s);
String toBeCapped = "i want this sentence capitalized";
String[] tokens = toBeCapped.split("//s");
toBeCapped = "";
for(int i = 0; i < tokens.length; i++){
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();
String toUpperCaseFirstLetterOnly(String str) {
String[] words = str.split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++) {
ret.append(Character.toUpperCase(words[i].charAt(0)));
ret.append(words[i].substring(1));
if(i < words.length - 1) {
ret.append('' '');
}
}
return ret.toString();
}
package corejava.string.intern;
import java.io.DataInputStream;
import java.util.ArrayList;
/*
* wap to accept only 3 sentences and convert first character of each word into upper case
*/
public class Accept3Lines_FirstCharUppercase {
static String line;
static String words[];
static ArrayList<String> list=new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) throws java.lang.Exception{
DataInputStream read=new DataInputStream(System.in);
System.out.println("Enter only three sentences");
int i=0;
while((line=read.readLine())!=null){
method(line); //main logic of the code
if((i++)==2){
break;
}
}
display();
System.out.println("/n End of the program");
}
/*
* this will display all the elements in an array
*/
public static void display(){
for(String display:list){
System.out.println(display);
}
}
/*
* this divide the line of string into words
* and first char of the each word is converted to upper case
* and to an array list
*/
public static void method(String lineParam){
words=line.split("//s");
for(String s:words){
String result=s.substring(0,1).toUpperCase()+s.substring(1);
list.add(result);
}
}
}
public static String toTitleCase(String word){
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
public static void main(String[] args){
String phrase = "this is to be title cased";
String[] splitPhrase = phrase.split(" ");
String result = "";
for(String word: splitPhrase){
result += toTitleCase(word) + " ";
}
System.out.println(result.trim());
}