martes, abril 16, 2024

Concatenar textos NSString en XCode

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"

 

Roy Rojas
Roy Rojashttp://www.dotnetcr.com
Con más de 20 años de experiencia en programación, experto en lenguajes .NET, VB, C#, ASP.NET, Xamarin, XCode, DBA en SQL Server. Creador de dotnetcr.com, sitio web para programadores en español. royrojas.com | dotnetcr.com | GitHub
Roy Rojas
Roy Rojashttp://www.dotnetcr.com
Con más de 20 años de experiencia en programación, experto en lenguajes .NET, VB, C#, ASP.NET, Xamarin, XCode, DBA en SQL Server. Creador de dotnetcr.com, sitio web para programadores en español. royrojas.com | dotnetcr.com | GitHub