标签:
1.编写一个程序,使用NSString和NSMutableString实例化一些NSString类的对象,然后比较其是否相等,大小。实例化一个NSMutableString的对象,然后将之前的NSString对象加入其中,然后再删除几个,要求使用NSRange结构体
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool
{
// NSString
NSString *str1=@"hello word!";
NSString *str2=@"Hello Word!";
// isEqualToString 区分大小写的
// 判断是否相等
if ([str1 isEqualToString:str2]==YES)
{
NSLog(@"相等");
}
else
{
NSLog(@"不相等");
}
//区分大小写的比较大小
if ([str1 compare:str2]==NSOrderedAscending)
{
NSLog(@"str1>str2");
}
else if([str1 compare:str2]==NSOrderedSame)
{
NSLog(@"str1=str2");
}
else
{
NSLog(@"str1<str2");
}
// 不区分大小写的比较大小
if ([str1 compare:str2 options:NSCaseInsensitiveSearch]==-1)
{
NSLog(@"str1<str2");
}
else if ([str1 compare:str2 options:NSCaseInsensitiveSearch]==0)
{
NSLog(@"str1=str2");
}
else
{
NSLog(@"str1>str2");
}
// NSMutableAttributedString
NSMutableString *str3=[NSMutableString stringWithCapacity: 100];
[str3 appendFormat:@"hello word!"];
[str3 appendFormat:@"Hello Word!"];
[str3 appendString:@"my name isxyl"];
[str3 appendString:@"age is 24"];
[str3 insertString:@"addess is guiyang" atIndex:20];
NSRange range1=[str3 rangeOfString:@"addess is guiyang"];
NSRange range2=[str3 rangeOfString:@"hello word!"];
[str3 deleteCharactersInRange:range1];
[str3 deleteCharactersInRange:range2];
NSLog(@"%@",str3);
NSLog(@"%ld",[str3 length]);
}
return 0;
}
2.编写程序,将”Hello World and Sunshine.”字符串中的”World”替换为”lamco”, 并将替换前和替换后的字符串输出 本题要求做两次,使用NSString两种替换方法完
方法一:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSString *str1=@"hello World and Sunshine";
NSLog(@"替换前:%@",str1);
NSString*str2=[str1 stringByReplacingOccurrencesOfString:@"World" withString:@"lamco"];
NSLog(@"替换后:%@",str2);
}
return 0;
}
方法二:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSMutableString *str1=[NSMutableString stringWithCapacity:100];
[str1 appendString:@"hello World and Sunshine"];
NSLog(@"替换前:%@",str1);
// 要注意替换的字符串
NSRange range1=[str1 rangeOfString:@"World"];
[str1 replaceCharactersInRange:range1 withString:@"lamco"];
NSLog(@"替换后:%@",str1);
NSLog(@"%ld",[str1 length]);
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/bolin-123/p/5107500.html