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.

回應 (Leave a comment)