Concatenar textos NSString en XCode

0
3495

Para concatenar strings en XCode ya se han definido funciones especificas, algunas permite concatenar N cantidad de variables o palabras y otras solo permite concatenar 2 variables y obtener como resultado un NSString.

En este ejemplo vamos a explicar tres opciones :

– stringByAppendingString:  Retorna un string luego de que a un string base se le agrega otro

– stringByAppendingFormat: Retorna un string pero se le pueden concatenar múltiples variables, siempre con un string base.

– stringByAppendingFormat: Permite concatenar múltiples variables strings y retorna un string concatenado.

 

Aquí explicamos las 3 opciones del ejemplo

stringByAppendingString: Retorna un string luego de que a un string base se le agrega otro.

– (NSString *)stringByAppendingString:(NSString *)
– textoBaseOriginal stringByAppendingString: textoAConcatenar

NSString *texto1 = @"Texto 01 ";
NSString *texto2 = @"Concatenado 02";
NSString *textoRetorno = [texto1 stringByAppendingString:texto2];
 
// textoRetorno retorna: "Texto 01 Concatenado 02"

stringByAppendingFormat: Igual al anterior retorna un string pero en este se le pueden concatenar múltiples variables, siempre con un string base.

NSString *texto1 = @"Texto 01 ";
NSString *texto2 = @"Texto 02";
NSInteger numero = 1234;
NSString * textoRetorno = @"Mi texto: ";
 
textoRetorno = [textoRetornado stringByAppendingFormat:@"%@ %@ %d",texto1, texto2, numero];
 
// textoRetorno retorna: "Mi texto: Texto 01 Texto 02 1234"

Como se puede ver en el ejemplo a la variable textoRetorno se le concatenan 3 variables, dos string y un numero entero. Pueden ser N variables, separadas por coma, siempre que estén definidas en el formato del string.

%@ representa variables tipo string
%d variables tipo entero
%f variables tipo float o decimales

stringWithFormat: Permite concatenar múltiples variables strings y retorna un string concatenado. No ocupa un string base.

NSString *texto1 = @"Texto 01 ";
NSString *texto2 = @"Texto 02";
NSString *texto3 = @"Texto 03";
NSInteger numero = 1234;
NSString * textoRetorno = @"";
 
textoRetorno = [NSString stringWithFormat:@"Mi texto: %@ %@ %@ %d", texto1, texto2, texto3, numero];
 
// textoRetorno retorna: "Mi texto: Texto 01 Texto 02 Texto 03 1234"

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here