Search code examples
iosobjective-cnsstring

Remove semicolon and brackets from string


i have a string like this:

{
    Result1 = G;
    "Result2" = "";
    Result3 = "1.03";
    Result4 = 6212753389;
}

how i get result like this:

    Result1 = G
    Result2 = 
    Result3 = 1.03
    Result4 = 6212753389

NOTE: i am trying all suggestion of NSCharacterSet.

please help me and thank in advance.


Solution

  • Wrong question, or better said: wrong approach or wrong interpretation of your issue. Don't worry, that's okay, I'll explain why.

    This is the typical result of:

    NSString *str = [myDict description];
    

    Or

    NSString *str = [NSString stringWithFormat:@"%@", myDict]; //(which relies on `description` method of `NSDictionary`, that's just an hidden call.
    

    See the doc:

    NSString uses a format string whose syntax is similar to that used by other formatter objects. It supports the format characters defined for the ANSI C function printf(), plus %@ for any object (see String Format Specifiers and the IEEE printf specification). If the object responds to descriptionWithLocale: messages, NSString sends such a message to retrieve the text representation. Otherwise, it sends a description message. Localizing String Resources describes how to work with and reorder variable arguments in localized strings. Source

    Almost never relies on description, that's more for Debugging purpose. For instance, in my experience, Apple changed at least once the description of an object. In ExternalAccessory.framework, you could get the MAC Address of a device with description (which is not the politic of Apple), but only on certain iOS version, and once the error spotted, it was removed. So if you had code relying on it, bad luck.

    What you want is a custom "print" of your NSDictionary. What you can do:

    NSMutableString *str = [[NSMutableString alloc] init];
    for (id aKey in myDict)
    { 
        [str appendFormat:@"\t%@ = %@\n", aKey, myDict[aKey]];
    }
    

    This add an extra "\n" at the end of the NSString. You can remove it, or use instead of NSMutableArray:

    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (id aKey in myDict)
    { 
        NSString *aLine = [NSString stringWithFormat:@"\t%@ = %@", aKey, myDict[aKey]];
        [array addObject:aLine];
    }
    NSString *str = [array componentsJoinedByString:@"\n"];
    

    Side note: Why do "Result2" had quotes discussions: Why do some dictionary keys have quotes and others don't when printing from debugger?

    Why does string show up in NSDictionary with quotes, but others don't?