2014
Jan
30
NSString 基本使用
固定字串相加
Fixed String append
- NSString *str = @"a" @"b";
- //str = ab
字串相加 stringByAppendingString
String append
- NSString *str = [[NSString alloc] init];
- str = @"a";
- str = [str stringByAppendingString:@"b"];
- NSLog(@"%@", str);
字串相加 stringWithFormat
另外一种相字串相加起来的方式,是使用 stringWithFormat ,这个方式有点像 C 语言的 sprintf 。
String stringWithFormat
- NSString *str = [[NSString alloc] init];
- str = @"a";
- NSString *str2 = @"b";
- NSString *str3 = @"c";
- NSString *result = [NSString stringWithFormat:@"%@/%@/%@", str, str2, str3];
- NSLog(@"result = %@", result);
- //result = a/b/c
字串相加 Macro - Define
每次将字串加起来时,都要写好长的指程式码,透过 Define 的方式,将程式码缩短。
AppendString Macro
- #define AString(A,B) [(A) stringByAppendingString:(B)]
- NSString *str = @"a";
- NSString *str2 = @"b";
- NSLog(@"append = %@", AString(str, str2));
多行字串
Multi-line content
- NSString* content = {
- @"<html>\n"
- @"<head></head>\n"
- @"<body>\n"
- @"<div> string </div>\n"
- @"</body>\n"
- };
- NSLog(@"%@", content);
字串取代
string replace
- NSString *str = @"Today is a good day.";
- str = [str stringByReplacingOccurrencesOfString:@"good" withString:@"bad"];
- NSLog(@"%@", str);
- // str = Today is a bad day.