ios – 获取NSString的前两个字符

我有一个字符串,我试图获得前2个字符和字符串的其余部分.这就是我试图这样做的方式:
Nsstring *textAll = [arrayOfMessages objectAtIndex:indexPath.row];
Nsstring *textMessage = [textAll substringFromIndex:2];
Nsstring *textType = [textAll substringToIndex:1];

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

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

解决方法

获取字符串的前两个字符,您需要:
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个字符,否则会引发异常.)

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...