如何在iOS(目标C)中将字符从一个位置修剪到另一个位置?

Posted

技术标签:

【中文标题】如何在iOS(目标C)中将字符从一个位置修剪到另一个位置?【英文标题】:How to trim characters from a position to another position in iOS (Objective C)? 【发布时间】:2016-05-02 10:45:35 【问题描述】:

我的问题是,我想从字符串中删除一些字符。我的字符串包含 xml。所以我需要修剪从 xml 开始标签到结束标签的字符。我该怎么做?

例如:我的字符串包含以下 xml 代码。

<CategoriesResponse xmlns="https://abc.defg.com/hijk">
    <MainCategories>
        <CatID xsi:type="xsd:int">178</CatID>
        <CatID xsi:type="xsd:int">150</CatID>
        <CatID xsi:type="xsd:int">77</CatID>
        <CatID xsi:type="xsd:int">33</CatID>
        <CatID xsi:type="xsd:int">179</CatID>
    </MainCategories>
<SubCategories>
    //some needed elements should not be trimmed.
</SubCategories>

我需要从开始标签&lt;MainCategories&gt; 修剪到结束标签&lt;/MainCategories&gt;。 怎么做??所以这里我的起始字符是&lt;MainCategories,结束字符是/MainCategories&gt;

【问题讨论】:

NSXMLParser 怎么样? 我在 xml 解析器中解析响应。它运作良好。但问题是MainCategory 标签之间的CatIDs 是不需要的。但需要SubCategories 内的CatIDs。当我使用NSXMLParser 时,所有CatIDs 都会被解析。这让我一团糟 您只需保留一个标志,表明您是否在MainCategories 标签内。您可以从对委托 didStartElementdidEndElement 方法的调用中了解这一点 是的,我改变了一点,就像你说的那样 【参考方案1】:

试试这个

NSString *str = @"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";


NSRange startRange = [str rangeOfString:@"<MainCategories>"];
NSRange endRange = [str rangeOfString:@"</MainCategories>"];
NSString *replacedString = [str stringByReplacingCharactersInRange:NSMakeRange(startRange.location, (endRange.location+endRange.length)-startRange.location) withString:@""];
NSLog(@"%@",replacedString);

希望这会有所帮助。

【讨论】:

哦,我的朋友,它很快。我在做目标 c。我不知道斯威夫特。 哦,我的上帝...哦,它工作了..它工作了。谢啦。如果可能的话 5 票,我会给你 5。我被搞砸了【参考方案2】:

试试下面的代码:

NSString *strXml=@"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";

                       strXml=[strXml stringByReplacingOccurrencesOfString:@"<MainCategories>" withString:@"<MainCategories"];

                       strXml=[strXml stringByReplacingOccurrencesOfString:@"</MainCategories>" withString:@"/MainCategories>"];

                       NSLog(@"%@",strXml);

希望它会有所帮助:)

【讨论】:

它有帮助。但实际上我希望删除标签(MainCategories 和 /MainCategories)之间的那些字符(CatID 标签),包括该标签。

以上是关于如何在iOS(目标C)中将字符从一个位置修剪到另一个位置?的主要内容,如果未能解决你的问题,请参考以下文章

如何在iOS中将一张图像合并到另一张图像的中心?

如何在同一个表中将数据从一列复制到另一列?

如何在 Qt 中将数据从一种形式传递到另一种形式?

如何在 ios 中将变量从 javascript 传递到目标 C 和目标 C 到 Javascript

如何在iOS中将字符串转换为xml? (目标 C,xcode 7.2)

如何在 Java 中将文件从一个位置移动到另一个位置?