2014
Jan
30

网页好读版

NSString 基本使用

固定字串相加

Fixed String append
  1. NSString *str = @"a" @"b";
  2. //str = ab

字串相加 stringByAppendingString

String append
  1. NSString *str = [[NSString alloc] init];
  2. str = @"a";
  3. str = [str stringByAppendingString:@"b"];
  4. NSLog(@"%@", str);

字串相加 stringWithFormat

另外一种相字串相加起来的方式,是使用 stringWithFormat ,这个方式有点像 C 语言的 sprintf 。

String stringWithFormat
  1. NSString *str = [[NSString alloc] init];
  2. str = @"a";
  3. NSString *str2 = @"b";
  4. NSString *str3 = @"c";
  5. NSString *result = [NSString stringWithFormat:@"%@/%@/%@", str, str2, str3];
  6. NSLog(@"result = %@", result);
  7. //result = a/b/c

字串相加 Macro - Define

每次将字串加起来时,都要写好长的指程式码,透过 Define 的方式,将程式码缩短。

AppendString Macro
  1. #define AString(A,B) [(A) stringByAppendingString:(B)]
  2. NSString *str = @"a";
  3. NSString *str2 = @"b";
  4. NSLog(@"append = %@", AString(str, str2));
  5.  

多行字串

Multi-line content
  1. NSString* content = {
  2. @"<html>\n"
  3. @"<head></head>\n"
  4. @"<body>\n"
  5. @"<div> string </div>\n"
  6. @"</body>\n"
  7. };
  8.  
  9. NSLog(@"%@", content);

字串取代

string replace
  1. NSString *str = @"Today is a good day.";
  2. str = [str stringByReplacingOccurrencesOfString:@"good" withString:@"bad"];
  3. NSLog(@"%@", str);
  4. // str = Today is a bad day.

网页好读版