¿Cómo poner en mayúscula la primera palabra de la oración en Objective-C?
Ya he encontrado cómo poner en mayúscula todas las palabras de la oración, pero no solo la primera palabra.
NSString *txt =@"hi my friends!"
[txt capitalizedString];
No quiero cambiar a minúsculas y poner en mayúscula el primer carácter. Me gustaría poner en mayúscula la primera palabra solo sin cambiar las otras.
9 answers
Aquí hay otra oportunidad:
NSString *txt = @"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];
Para lenguaje Swift:
txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 14:57:50
La respuesta aceptada es incorrecta. Primero, no es correcto tratar las unidades de NSString
como "caracteres" en el sentido que un usuario espera. Hay parejas sustitutas. Hay combinaciones de secuencias. Dividirlos producirá resultados incorrectos. Segundo, no es necesariamente el caso que poner en mayúscula el primer carácter produce el mismo resultado que poner en mayúscula una palabra que contiene ese carácter. Los idiomas pueden ser sensibles al contexto.
La forma correcta de hacer esto es obtener los frameworks para identifique palabras (y posiblemente oraciones) de la manera apropiada para el lugar. Y también para capitalizar en la manera local-apropiada.
[aMutableString enumerateSubstringsInRange:NSMakeRange(0, [aMutableString length])
options:NSStringEnumerationByWords | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[aMutableString replaceCharactersInRange:substringRange
withString:[substring capitalizedStringWithLocale:[NSLocale currentLocale]]];
*stop = YES;
}];
Es posible que la primera palabra de una cadena no es la misma que la primera palabra de la primera frase de una cadena. Para identificar la primera (o cada) oración de la cadena y luego poner en mayúscula la primera palabra de esa (o esas), luego rodear la anterior en una invocación externa de -enumerateSubstringsInRange:options:usingBlock:
usando NSStringEnumerationBySentences | NSStringEnumerationLocalized
. En la invocación interior, pasar el substringRange
proporcionado por el invocación externa como argumento de rango.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-12 10:40:29
Use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
Y poner en mayúscula el primer objeto en la matriz y luego usar
- (NSString *)componentsJoinedByString:(NSString *)separator
Para unirse a ellos de nuevo
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-12 11:58:04
pString = [pString
stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[pString substringToIndex:1] capitalizedString]];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-12 10:13:15
Usted puede usuario con la expresión regular he hecho es trabajos para mí simple usted puede pegar debajo del código +(NSString*)CaptializeFirstCharacterOfSentence: (NSString*)sentence{
NSMutableString *firstCharacter = [sentence mutableCopy];
NSString *pattern = @"(^|\\.|\\?|\\!)\\s*(\\p{Letter})";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
[regex enumerateMatchesInString:sentence options:0 range:NSMakeRange(0, [sentence length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
//NSLog(@"%@", result);
NSRange r = [result rangeAtIndex:2];
[firstCharacter replaceCharactersInRange:r withString:[[sentence substringWithRange:r] uppercaseString]];
}];
NSLog(@"%@", firstCharacter);
return firstCharacter;
} // Llamar a este método NSString * resultSentence =[ UserClass CaptializeFirstCharacterOfSentence: yourTexthere];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-26 09:49:45
Por el bien de tener opciones, yo sugeriría:
NSString *myString = [NSString stringWithFormat:@"this is a string..."];
char *tmpStr = calloc([myString length] + 1,sizeof(char));
[myString getCString:tmpStr maxLength:[myString length] + 1 encoding:NSUTF8StringEncoding];
int sIndex = 0;
/* skip non-alpha characters at beginning of string */
while (!isalpha(tmpStr[sIndex])) {
sIndex++;
}
toupper(tmpStr[sIndex]);
myString = [NSString stringWithCString:tmpStr encoding:NSUTF8StringEncoding];
Estoy en el trabajo y no tengo mi Mac para probar esto, pero si recuerdo correctamente, no podría usar [myString cStringUsingEncoding:NSUTF8StringEncoding]
porque devuelve un const char *
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-12 19:47:24
En swift puede hacerlo de la siguiente manera usando esta extensión:
extension String {
func ucfirst() -> String {
return (self as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: (self as NSString).substringToIndex(1).uppercaseString)
}
}
Llamando a tu cadena de esta manera:
var ucfirstString:String = "test".ucfirst()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-17 16:03:57
Una solución alternativa en Swift:
var str = "hello"
if count(str) > 0 {
str.splice(String(str.removeAtIndex(str.startIndex)).uppercaseString, atIndex: str.startIndex)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-12 09:45:13
Sé que la pregunta pide específicamente una respuesta Objetiva C, sin embargo aquí hay una solución para Swift 2.0:
let txt = "hi my friends!"
var sentencecaseString = ""
for (index, character) in txt.characters.enumerate() {
if 0 == index {
sentencecaseString += String(character).uppercaseString
} else {
sentencecaseString.append(character)
}
}
O como extensión:
func sentencecaseString() -> String {
var sentencecaseString = ""
for (index, character) in self.characters.enumerate() {
if 0 == index {
sentencecaseString += String(character).uppercaseString
} else {
sentencecaseString.append(character)
}
}
return sentencecaseString
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-11 00:45:57