Object-C学习笔记七-----Foundation Kit快速教程NSString and NSMutableString

在Foundation 框架中有很多有用的,面向数据的低级类和数据类型。其中比较重要的是。NSString NSArray NSEnumerator NSNumber等。

首先我们下熟悉一下常用的一些结构(struct)

1。范围的作用,NSRange 表示相关事物的范围。通常是字符串里的字符范围或者数组里的元素范围。

typedef _NSRange//表示相关事物的范围

{

    unsigned int location;//表示位置

    unsigned int length;//表示元素个数

}NSRange;

最常用的赋值方式时调用NSMakeRange();

[anObject flarbulatewithRange:NSMakeRange(13,15)];


2。几何数据类型 NSPoint(代表笛卡尔平面中的坐标) NSSize(存储长度和宽度)

如果要赋值,使用的时NSMakePoint() NSMakeSize()。


3。NSString时不可变的。object-c提供了NsMutableString子类可以改变。就像在C#中string类也是不可变的,而stringBuilder是可变的类似。

a。stringWithFormat方法可以创建NSString。这个方法是一个类方法。

NSString *height;

height=[NSStringstringWithFormat:@"you height is %d feet,%d inches",5,11];

b。length方法返回的是字符串中的字符个数

if([heightlength]>5)

    NSLog(@"wow,you'er really tall!");

c。比较通常常用两种比较方式。isEqualToString方法和"=="方法 ,compare方法是区别大小写的比较。

   NSString *thing1=@"hello 5";

    NSString *thing2;

    thing2=[NSString stringWithFormat:@"hello %d",5];

    if([thing1 isEqualToString:thing2])//判断两个字符串是否时同一事物

        NSLog(@"They are the same!");

    if(thing1==thing2)                  //判断是否时同一对象。

        NSLog(@"They are the same object!");

-(NSComparisonResult) compare:(NSString *) string options:(unsigned) mask

 if([thing1compare:thing2options:NSCaseInsensitiveSearch|NSNumericSearch])

       NSLog(@"They match!");

d。字符串是否包含别的字符串 hasPrefix 判断字符串开头,hasSuffix 判断字符串结尾。 rangeOfString字符串是否包含其他字符串。

  NSString *filename=@"draft-chapter.pages";

    if ([filename hasPrefix:@"draft"]) {

       NSLog(@"Include the word");

    }

    if (![filename hasSuffix:@".mov"]) {

       NSLog(@"Include the  no word");

    }


--------------------------------------------------------------------------------------

可变字符串NSMutableString

stringWithCapacity 创建一个NSMutableString,可以通过appendString和appendFormat来附加新字符串。

   NSMutableString *str;

    str=[NSMutableStringstringWithCapacity:50];

    [strappendString:@"Hello there "];//复制到接收对象的末尾。参数是string

    [strappendFormat:@"Human %d",39];//将格式化字符串加在接收字符串的结尾。

    NSLog(@"%@",str);


deleteCharactersInRange方法删除字符串中的字符。

    NSMutableString *friends;

    friends=[NSMutableStringstringWithCapacity:50];

    [friendsappendString:@"James BethLynn Jack Evan"];

    NSLog(@"%@",friends);

    NSRange range;

    range =[friends rangeOfString:@"Jack"];

    range.length++;//因为后面还有一个空格所以length+1

    [friendsdeleteCharactersInRange:range];

    NSLog(@"%@",friends);



NSMutableString是NSString的子类,所以NSString里面的方法都可以在NSMutableString中使用。


1。类方法前面用+号,而实例方法用-号。

2。isEqualToString方法和“==”方法的区别。

3。字符串包含其他字符串。

4。删除字符串中的字符。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值