0

I have the following string:

callback({"Outcome":"Success", "Message":null, "Identity":"Request", "Delay":0.002, "Symbol":"AAPL", "CompanyName":"Apple Inc.", "Date":"1\/13\/2011", "Time":"4:02:36 PM", "Open":344.6, "Close":345.93, "PreviousClose":344.42, "High":346.63, "Low":343.86, "Last":345.93, "Change":1.51, "PercentChange":0.438, "Volume":785960})

I want my final string to not contain callback( and the the last ) at the end of the string. How can I modify this NSString?

3 Answers 3

3

NSScanner is a good fit for this sort of thing.

NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:fullString];
[scanner scanUpToString:@"{" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:@")" intoString:&json];

NSLog(@"json = %@", json);
Sign up to request clarification or add additional context in comments.

1 Comment

Or, scan up to the (, then scan it into the same black hole, then scan up to the ). Either way, though, this will fail if the JSON contains a ) (e.g., within a string).
2

Make an NSMutableString out of it, called string. i.e. NSMutableString *string = [NSMutableString stringWithString:myString];.

Then do string = [string substringToIndex:[string length]-1]; and then string = [string substringFromIndex:9]; or some such.

Or, again create an NSMutableString instance with your NSString instance, and call [string replaceOccurrencesOfString:@"callback(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [string length])]; and [string replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [string length])];. This might be preferred.

Either way, then create an NSString instance with the new string, something like goodString = [NSString stringWithString:string]; if you need an NSString out of this.

2 Comments

That will not mutate the original string even if you're using an NSMutableString.
@Chuck: That's right. The original string is of course unchanged. It's also not necessary to mutate anything. We also don't need NSMutableStrings here, so my post is overkill. However, Alam seems to be under the impression that you can modify an NSString which you can't.
1

You can't modify an NSString (only an NSMutableString), but you can use [string substringWithRange:NSMakeRange(9, [string length] - 10)]. To actually mutate an NSMutableString, you'd have to use two deleteCharactersInRange: calls to trim the parts you don't want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.