如何从Web服务响应中的NSString中删除换行符?

时间:2012-03-14 11:02:31

标签: iphone nsstring

我目前正在收到包含许多新行字符的Webservice响应。我尝试了以下方法,但仍然无法消除新行字符。

1)

responseString = [responseString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

2)

responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

3)

NSRange foundRange = [responseString rangeOfString:@"\n"];
    if (foundRange.location != NSNotFound)
        [responseString stringByReplacingOccurrencesOfString:@"\n"
                                            withString:@""
                                               options:0 
                                                 range:foundRange];

我的Webservice respsonse采用这种格式。

META NAME="ColdFusionMXEdition" CONTENT="ColdFusion DevNet Edition - Not for Production Use."?      


    wddxPacket version='1.0'><header/><data><string>{"MESSAGE":"","CODE":1,"RESPONSE":{"FILENAME":"CustomerSkillsIntro","PLAYLIST":[{"TIMEOUT":73,"TITLE":"Greet","QUESTIONNUMBER":1,"TIMEIN":71,"VALIDRESPONSE":1},{"TIMEOUT":77,"TITLE":"Have Name Tag","QUESTIONNUMBER":2,"TIMEIN":74,"VALIDRESPONSE":1},{"TIMEOUT":83,"TITLE":"Greet","QUESTIONNUMBER":3,"TIMEIN":78,"VALIDRESPONSE":1},{"TIMEOUT":112,"TITLE":"Helping Do My Job","QUESTIONNUMBER":4,"TIMEIN":109,"VALIDRESPONSE":1},{"TIMEOUT":134,"TITLE":"Greet Happily","QUESTIONNUMBER":5,"TIMEIN":131,"VALIDRESPONSE":1},{"TIMEOUT":144,"TITLE":"Stay cheerful when resident is crabby","QUESTIONNUMBER":6,"TIMEIN":141,"VALIDRESPONSE":1},{"TIMEOUT":154,"TITLE":"Bond with the new resident","QUESTIONNUMBER":7,"TIMEIN":151,"VALIDRESPONSE":1},...................

我的要求是只从{"MESSAGE":"","CODE":1,到结尾捕获字符串的一部分。但是我在所需的部分之前得到了太多的空格和新的行字符。

1 个答案:

答案 0 :(得分:1)

看起来您可以通过从首次出现'{'到最后一次出现'}'的字符串来简化您的问题。

以下代码通过不同的方法确保您想要的结果。如果你说你只需要“从{"MESSAGE":"","CODE":1,到最后”的部分,为什么还要去除空格。

NSRange start = [responseString rangeOfString:@"{"];
NSRange end = [responseString rangeOfString:@"}" options:NSBackwardsSearch];
NSString *result = nil;

if ((start.location != NSNotFound)&&(start.location != NSNotFound))
{
    NSRange resultRange = NSMakeRange(start.location,end.location - start.location + 1);
    result = [responseString substringWithRange: resultRange];
    NSLog (@"returning with result: %@", result);
}
else 
{
    NSLog (@"abort mission");
}