10

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

NSString *textAll = [arrayOfMessages objectAtIndex:indexPath.row];
NSString *textMessage = [textAll substringFromIndex:2];
NSString *textType = [textAll substringToIndex:1];

textAll 具有这种形式:HE消息本身.....

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

4

1 回答 1

25

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

NSString *textType = [textAll substringToIndex:2];  // <-- 2, not 1

从文档中:

substringToIndex:

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

(请注意,该方法要求字符串至少有 2 个字符长,否则会引发异常。)

于 2013-11-02T21:08:54.550 回答