ios – 获取NSString的前两个字符

前端之家收集整理的这篇文章主要介绍了ios – 获取NSString的前两个字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个字符串,我试图获得前2个字符和字符串的其余部分.这就是我试图这样做的方式: @H_301_2@NSString *textAll = [arrayOfMessages objectAtIndex:indexPath.row]; NSString *textMessage = [textAll substringFromIndex:2]; NSString *textType = [textAll substringToIndex:1];

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

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

解决方法

获取字符串的前两个字符,您需要: @H_301_2@NSString *textType = [textAll substringToIndex:2]; // <-- 2,not 1

从文档:

substringToIndex:

Returns a new string containing the characters of
the receiver up to,but not including,the one at a given index.

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

猜你在找的iOS相关文章