美文网首页
字符串 转utf8和unicode再转回来

字符串 转utf8和unicode再转回来

作者: 杜兰特的大胡子和哈登的包 | 来源:发表于2019-07-22 11:18 被阅读0次

    //utf8转中文

    NSString* strA = [@"%E4%B8%AD%E5%9B%BD"stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    //中文转unicode

    NSString *strB = [@"中国"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    ios9之后

    NSString *urlStr = @"url地址";
    

    //中文转utf8

    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    

    //utf8转中文

    urlStr = [urlStr stringByRemovingPercentEncoding];
    

    //中文转成unicode

    - (NSString *) utf8ToUnicode:(NSString *)string{
    
        NSUInteger length = [string length];
        NSMutableString *str = [NSMutableString stringWithCapacity:0];
        for (int i = 0;i < length; i++){
            NSMutableString *s = [NSMutableString stringWithCapacity:0];
            unichar _char = [string characterAtIndex:i];
            // 判断是否为英文和数字
            if (_char <= '9' && _char >='0'){
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
            }else if(_char >='a' && _char <= 'z'){
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
            }else if(_char >='A' && _char <= 'Z')
            {
                [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
            }else{
                // 中文和字符
                [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
                // 不足位数补0 否则解码不成功
                if(s.length == 4) {
                    [s insertString:@"00" atIndex:2];
                } else if (s.length == 5) {
                    [s insertString:@"0" atIndex:2];
                }
            }
            [str appendFormat:@"%@", s];
        }
        return str;
    }
    

    相关文章

      网友评论

          本文标题:字符串 转utf8和unicode再转回来

          本文链接:https://www.haomeiwen.com/subject/ppuilctx.html