<p style="margin-top: 0px; margin-bottom: 0px;"><pre name="code" class="objc"><span style="font-family:KaiTi_GB2312;font-size:18px;">// 创建字符串
NSString *str1 = @"QAQ";
NSString *str3 = @"人人";
NSString *str4 = @"iphone6Plus";
</span><h3><span style="font-family:KaiTi_GB2312;font-size:18px;"> <span style="font-weight: normal;">// 打印</span></span></h3><span style="font-family:KaiTi_GB2312;font-size:18px;"> NSLog(@"%@", str3);
// 取字符串长度
NSLog(@"length: %lu", str3.length);
// 取子串
// fromIndex 从当前下标处取到字符串结尾 包含当前下标
NSString *str5 = [str4 substringFromIndex:2];
NSLog(@"%@", str5);
// toIndex 从字符串的开头取到某个下标处结束 不包含当前下标
NSString *str6 = @"hahahaha";
NSString *str7 = [str6 substringToIndex:6];
NSLog(@"%@", str7);
// withRange
// 通过范围结构体取子串
// NSRange r = {2, 5};
NSString *str8 = [str6 substringWithRange:NSMakeRange(1, 5)];
NSLog(@"%@", str8);
// 拼接字符串
NSString *str9 = [str4 stringByAppendingString:@"5288"];
NSLog(@"str9: %@", str9);
// 替换字符串
NSString *str10 = [str9 stringByReplacingOccurrencesOfString:@"6Plus" withString:@"7S"];
NSLog(@"str10: %@", str10);
// 字符串的相等判断
NSString *str11 = @"123";
NSString *str12 = @"123";
if (str11 == str12) {
NSLog(@"两个字符串对象的地址相同");
}
if ([str11 isEqualToString:str12]) {
NSLog(@"两个字符串对象的内容相同");
}
// 判断前缀/后缀
if ([str10 hasPrefix:@"i"]) {
NSLog(@"有前缀");
}
if ([str10 hasSuffix:@"88"]) {
NSLog(@"有后缀");
}
// 字符串比较
NSString *str13 = @"iphone6";
NSString *str14 = @"iphone5S";
// 定义一个比较结果变量 用来存储字符串比较结果
NSComparisonResult result = [str13 compare:str14];
if (result == NSOrderedAscending)
{
NSLog(@"升序");
}
else if (result == NSOrderedDescending)
{
NSLog(@"降序");
}
else
{
NSLog(@"相同");
}
// 可变字符串 NSMutableString</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">
//创建可变字符串
NSMutableString *mStr = [NSMutableString string];
// 拼接
[mStr appendString:@"iphone"];
// 插入
[mStr insertString:@"android" atIndex:2];
// 删除
[mStr deleteCharactersInRange:NSMakeRange(2, 7)];
NSLog(@"mStr %@", mStr);
/*
* 可变和不可变的区别
* 不可变对像的操作 都是产生了新的对象 可变对象都是在原对象的基础上进行了操作
*/
/*
* 不可变数组 NSArray
* 数组中只能存放对象
*/
// 创建数组对象
NSArray *arr1 = [NSArray arrayWithObjects:@"哈喽", @"你好", @"哈哈哈", nil];
NSLog(@"%@", arr1);
// 元素个数
NSLog(@"count: %ld", arr1.count);
// 数组访问
NSLog(@"object: %@", [arr1 objectAtIndex:1]);
// 遍历数组
for (NSInteger i = 0; i < arr1.count; i++) {
NSLog(@"%@", [arr1 objectAtIndex:i]);
}<span style="color:#008400;">
</span></span>
// for in 的用法 遍历数组
for (NSString *s in arr1) {
NSLog(@"%@", s);
}