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.
回應 (Leave a comment)