1.判断字符串中是否包含中文
- (BOOL)isContainChinese
{
for (int i = 0; i < self.length; i++) {
unichar ch = [self characterAtIndex:i];
if (0x4E00 <= ch && ch <= 0x9FA5) {
return YES;
}
}
return NO;
}
2.将字符串中的中文编码
-(NSString *)stringByUrlEncodingChinese
{
// 不包含中文,直接返回
if (![self isContainChinese]) {
return self;
}
// 取出字符串中的中文,以及中文符号。
NSString *ChineseStr = @"";
for (int i = 0 ; i < self.length; i ++) {
NSString *str =[self substringWithRange:NSMakeRange(i, 1)];
for (int j = 0 ; j < str.length; j++) {
unichar ch = [str characterAtIndex:j];
if (0x4E00 <= ch && ch <= 0x9FA5) {
ChineseStr = [ChineseStr stringByAppendingString:str];
break;
}
}
}
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:ChineseStr] invertedSet];
return [self stringByAddingPercentEncodingWithAllowedCharacters:set];
}
3.test
NSLog(@"%@",[@"index.html#/汉字/?value=1&key=2/中文符号!@#¥%……&*()?》《:“|」「【】/English!@#$^&*(){}|<>?:" stringByUrlEncodingChinese]);
输出结果
index.html#/%E6%B1%89%E5%AD%97/?value=1&key=2/%E4%B8%AD%E6%96%87%E7%AC%A6%E5%8F%B7%EF%BC%81@#%C2%A5%%E2%80%A6%E2%80%A6&*%EF%BC%88%EF%BC%89%EF%BC%9F%E3%80%8B%E3%80%8A%EF%BC%9A%E2%80%9C%EF%BD%9C%E3%80%8D%E3%80%8C%E3%80%90%E3%80%91/English!@#$^&*(){}|<>?: