一起学Objective-C - String

来源:互联网 发布:火绒安全软件设置 编辑:程序博客网 时间:2024/05/22 00:08

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;

}