获取NSString的前两个字符

Ale*_*dro 7 ios

我有一个字符串,我试图获得前2个字符和字符串的其余部分.这就是我试图这样做的方式:

NSString *textAll = [arrayOfMessages objectAtIndex:indexPath.row];
NSString *textMessage = [textAll substringFromIndex:2];
NSString *textType = [textAll substringToIndex:1];
Run Code Online (Sandbox Code Playgroud)

textAll有这样的形式:消息本身.....

textType应该返回'HE'textMessage应该返回'消息本身.....'Textmessage现在给我消息,但我似乎无法获取textType ...

Mar*_*n R 23

要获取字符串的前两个字符,您需要:

NSString *textType = [textAll substringToIndex:2];  // <-- 2, not 1
Run Code Online (Sandbox Code Playgroud)

从文档:

substringToIndex:

返回一个新字符串,其中包含接收者的字符,但不包括给定索引处的字符.

(请注意,该方法需要字符串长度至少为2个字符,否则会引发异常.)