一起学Objective-C - String

1. String的重要性就不用提了。在Objective-C中,可以用两种方式处理String. 一种是C的char数组实现方式(需要用“STR”类型来替换char[]),另外一种是直接用强大NSString。

 

两种方式可以互相转换

char数组转NSString

char *function (void);

char *result;

NSString *string;

result = function ();

string = [NSString stringWithCString: result];

反之

char*result;

NSString*string;

 

string = @"Hi!";

result = [string cString];

 

2. 定义NSString

NSString *w = @"Brainstorm";

3. 格式化NSString

intqos = 5;

NSString*gprsChannel;

 

gprschannel = [NSString stringWithFormat: @"The GPRS channel is %d", 

                qos];

3. NSString嵌套NSString

NSString *one;

NSString *two;

 

one = @"Brainstorm";

two = [NSString stringWithFormat: @"Our trading name is %@", one];

4. 类似于Java中StringBuffer的NSMutableString

NSString*name = @"Brainstorm";

NSString*greeting = @"Hello";

NSMutableString*s;

 

s = AUTORELEASE ([NSMutableString new]);

[s appendString: greeting];

[s appendString: @", "];

[s appendString: name];

这和下面的代码效果是一样的

NSString *name = @"Brainstorm";

NSString *greeting = @"Hello";

NSMutableString *s;

 

s = [NSMutableString stringWithFormat: @"%@, %@", greeting, name];

5. 读写文件

 写文件

#include <Foundation/Foundation.h>

int main (void)

{

  CREATE_AUTORELEASE_POOL(pool);

  NSString *name = @"This string was created by GNUstep";

 

  if ([name writeToFile: @"/home/nico/testing" atomically: YES])

    {

      NSLog (@"Success");

    }

  else 

    {

      NSLog (@"Failure");

    }

  RELEASE(pool);

  return 0;

}

writeToFile:atomically: 返回YES代表成功, 返回NO代表失败.

如果atomically设成YES, 会先把string保存到临时文件,等成功以后再改名,这样可以只有写成功了才会替换已有的文件,是个不错的功能。

 

读文件时用stringWithContentsOfFile

 #include <Foundation/Foundation.h>

int main (void)

{

  CREATE_AUTORELEASE_POOL(pool);

  NSString *string;

  NSString *filename = @"/home/nico/test";

 

  string = [NSString stringWithContentsOfFile: filename];

  if (string == nil)

    {

      NSLog (@"Problem reading file %@", filename);

      /*

       * <missing code: do something to manage the error...>

       * <exit perhaps ?>

       */

    }

 

  /*

   * <missing code: do something with string...>

   */

 

  RELEASE(pool);

  return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值