ios NSString文字列の一般的な方法
2364 ワード
1.取得したウェブコードがGB 2312の場合、UTF-8形式コードに変換される.
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];
2.文字列が空か空白かを判断する
- (BOOL)isEmptyOrWhitespace {
// A nil or NULL string is not the same as an empty string
return 0 == self.length ||
![self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length;
}
3.url文字列符号化
- (id)urlEncoded {
CFStringRef cfUrlEncodedString = CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,NULL,
(CFStringRef)@"!#$%&'()*+,/:;=?@[]",
kCFStringEncodingUTF8);
NSString *urlEncoded = [NSString stringWithString:(NSString *)cfUrlEncodedString];
CFRelease(cfUrlEncodedString);
return urlEncoded;
}
4. NSStringからNSDataへの変換
- (NSData *)dataFormString:(NSString *)string
{
if(!string)
{
string = @"";
}
return [NSData dataWithBytes:[requestString UTF8String] length:strlen([requestString UTF8String])];
}