字符串修改不起作用?

时间:2015-11-05 12:02:18

标签: ios objective-c url-encoding

这是我的代码,在我的网址字符串中,空格不是由代码

编码的
NSString *str  = item.fileArtPath;
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set];
[str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *urlString = [NSURL URLWithString:str];

以下字符串:

http://xx.xx.xx.xxx:xx/xx/xx/xx/xxx/Audio Adrenaline.jpg
                                    ^^^^^^^^^^^^^^^^^^^^

使用字符串替换后,Audio后的空格未转换为%20。在调试urlStringnil为什么会这样?

3 个答案:

答案 0 :(得分:1)

来自NSString类参考

  

通过替换all返回从接收器创建的新字符串   不在指定集合中的字符,包含百分比编码字符。

意味着它不会置换它所要求的实例。您需要说str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];[str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

相同的内容

答案 1 :(得分:1)

回想一下,NSString 不可变。调用方法stringBy...返回修改后的字符串,而不是修改原始字符串。因此,您的代码应该按如下方式重写:

str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

答案 2 :(得分:1)

void BTreeNode::traverse()
{
    // There are n keys and n+1 children, travers through n keys
    // and first n children

    int i;

    for (i = 0; i < n; i++)
    {
        // If this is not leaf, then before printing key[i],
        // traverse the subtree rooted with child C[i].
        if (leaf == false)

            C[i]->traverse(); 
        cout << " " << keys[i];
    }


    // Print the subtree rooted with last child
    if (leaf == false)
        C[i]->traverse();
}