当不在Objective-C中修剪其他NSMutableString时,如何修剪NSMutableString

时间:2016-07-14 11:48:11

标签: ios objective-c xib

从NSMutableString中删除空格时遇到问题。 我正在使用这样的代码:

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if(!myMutableStringSiteObj)
        myMutableStringSiteObj = [[NSMutableString alloc] initWithString:string];
    else
    {
        [myMutableStringSiteObj appendString:string];
        NSString *trimmedString = [myMutableStringSiteObj stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [myMutableStringSiteObj setString:trimmedString];

        NSData *datasite = [myMutableStringSiteObj dataUsingEncoding:NSUTF8StringEncoding];
        responseSitedict = [NSJSONSerialization JSONObjectWithData:datasite options:0 error:nil];
        NSLog(@"JSON DATA = %@",responseSitedict);
    }

    myMutableStringObj=[[NSMutableString alloc]initWithString:string];
    NSLog(@"Array String: %@",myMutableStringObj);
    NSData *data = [myMutableStringObj dataUsingEncoding:NSUTF8StringEncoding];
    responsedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"JSON DATA = %@",responsedict);

    myMutableStringbranchObj=[[NSMutableString alloc]initWithString:string];
    NSLog(@"Array String: %@",myMutableStringbranchObj);
    NSData *databranch = [myMutableStringbranchObj dataUsingEncoding:NSUTF8StringEncoding];
    responsebranchdict = [NSJSONSerialization JSONObjectWithData:databranch options:0 error:nil];
    NSLog(@"JSON DATA = %@",responsebranchdict);
}

在这段代码中有三个字符串,一个字符串包含空格,另外两个字符串不包含空格。首先,它需要myMutableStringObj的Id,然后是myMutableStringbranchObj,然后是myMutableStringSiteObj。但是当它来到myMutableStringSiteObj应用程序时会崩溃,因为它包含空格。但修剪字符串的代码不起作用。

2 个答案:

答案 0 :(得分:0)

如果你想修剪一个字符串(删除第一个和最后一个空格),那么你可以使用以下函数。

 NSString *newString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

答案 1 :(得分:0)

试试这个有效  NSString * Spacetrimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];