¿cómo obtener los primeros tres caracteres de un NSString?


¿Cómo puedo devolver los tres primeros caracteres de una NSString?

Author: Abizern, 2011-03-14

3 answers

 mystr=[mystr substringToIndex:3];

Asegúrese de que su cuerda tiene al menos 3 cad.. o. e.se bloqueará la aplicación.

Aquí hay algunos otros enlaces para comprobar las operaciones de NSsting...

Link1

Link2

Apple Link

 253
Author: GameLoading,
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-01-30 15:39:25

Primero, debe asegurarse de que la cadena contenga al menos 3 caracteres:

NSString *fullString = /* obtain from somewhere */;
NSString *prefix = nil;

if ([fullString length] >= 3)
    prefix = [fullString substringToIndex:3];
else
    prefix = fullString;

substringToIndex: lanzará una excepción si el índice que proporcione está más allá del final de la cadena.

 60
Author: dreamlax,
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
2011-03-14 04:26:41

El camino correcto es:

text = [text substringToIndex:NSMaxRange([text rangeOfComposedCharacterSequenceAtIndex:2])];

SubstringToIndex de NSString está indexando por unidad de código, emoji toma dos unidades de código.

Asegúrese de revisar el índice usted mismo.

 2
Author: peak,
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-12-30 09:02:17