How can I parse this string using NSString? - objective-c

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?

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);

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.

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.

Related

Split string into parts

I want to split NSString into array with fixed-length parts. How can i do this?
I searched about it, but i only find componentSeparatedByString method, but nothing more. It's also can be done manually, but is there a faster way to do this ?
Depends what you mean by "faster" - if it is processor performance you refer to, I'd guess that it is hard to beat substringWithRange:, but for robust, easy coding of a problem like this, regular expressions can actually come in quite handy.
Here's one that can be used to divide a string into 10-char chunks, allowing the last chunk to be of less than 10 chars:
NSString *pattern = #".{1,10}";
Unfortunately, the Cocoa implementation of the regex machinery is less elegant, but simple enough to use:
NSString *string = #"I want to split NSString into array with fixed-length parts. How can i do this?";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: pattern options: 0 error: &error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
NSMutableArray *result = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
[result addObject: [string substringWithRange: match.range]];
}
Break the string into a sequence of NSRanges and then try using NSString's substringWithRange: method.
You can split a string in different ways.
One way is to split by spaces(or any character):
NSString *string = #"Hello World Obj C is Awesome";
NSArray *words = [string componentsSeparatedByString:#" "];
You can also split at exact points in a string:
NSString *word = [string substringWithRange:NSMakeRange(startPoint, FIXED_LENGTH)];
Simply put it in a loop for a fixed length and save to Mutable Array:
NSMutableArray *words = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
NSString *word = [string substringWithRange:NSMakeRange(i, FIXED_LENGTH)]; //you may want to make #define
[array addObject:word];
}
Hope this helps.

Cocoa xcode4.3 hide characters of a string

I am adding string into a pickerView like this :
NSString *string = [NSString stringWithFormat:#"%# %#", xxx, xxx];
[pickerViewObjects addObject:string];
what i want to do is to hide the first part of the string, or of there's something to use like charachterAtIndex it will be useful because the first part of my string has a specific number of characters.
Use this method to get "(whitespaces) John"
NSString *string = #"Hello John";
NSUInteger spacePosition = [string rangeOfString:#" "].location;
NSMutableString *newString = [[NSMutableString alloc]init ];
for (int i=0; i<spacePosition; i++)
[newString appendString:#" "];
NSString *otherPartofString = [string substringFromIndex:(spacePosition)];
[newString appendString:otherPartofString];
NSLog(#"new String is '%#'",newString);
[newString release];
You can use [string substringWithRange:NSMakeRange(start, count)], that way you will only get a new string that you can use for displaying.
you can do like this:
find the position of space between two strings like this:
NSUInteger spacePosition = [string rangeOfString:#" "].location
then use:
NSString *otherPartofString = [string substringFromIndex:(spacePosition+1)];

How to strip down the string?

I have a really long string, I just want to extract some certain string inside that string. How can I do that?
for example I have:
this is the image <img src="http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg"> and it is very beautiful.
and yes now i want to get substring this long string and get only http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg
Please show me how I can do this.
You can use regular expressions for this:
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:#"src=\"([^\"]*)\"" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *text = #"this is the image <img src=\"http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg\"> and it is very beautiful.";
NSArray *imgs = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
if (imgs.count != 0) {
NSTextCheckingResult* r = [imgs objectAtIndex:0];
NSLog(#"%#", [text substringWithRange:[r rangeAtIndex:1]]);
}
This regular expression is the heart of the solution:
src="([^"]*)"
It matches the content of the src attribute, and captures the content between the quotes (note a pair of parentheses). This caption is then retrieved in [r rangeAtIndex:1], and used to extract the part of the string that you are looking for.
You should use a regular expression, probably using the NSRegularExpression class.
Here's an example that does exactly what you want (from here):
- (NSString *)stripOutHttp:(NSString *)httpLine
{
// Setup an NSError object to catch any failures
NSError *error = NULL;
// create the NSRegularExpression object and initialize it with a pattern
// the pattern will match any http or https url, with option case insensitive
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?"
options:NSRegularExpressionCaseInsensitive
error:&error];
// create an NSRange object using our regex object for the first match in the string httpline
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:httpLine
options:0
range:NSMakeRange(0, [httpLine length])];
// check that our NSRange object is not equal to range of NSNotFound
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0)))
{
// Since we know that we found a match, get the substring from the parent
// string by using our NSRange object
NSString *substringForFirstMatch = [httpLine substringWithRange:rangeOfFirstMatch];
NSLog(#"Extracted URL: %#",substringForFirstMatch);
// return the matching string
return substringForFirstMatch;
}
return NULL;
}
NSString *urlString = nil;
NSString *htmlString = //Your string;
NSScanner *scanner = [NSScanner scannerWithString:htmlString];
[scanner scanUpToString:#"<img" intoString:nil];
if (![scanner isAtEnd]) {
[scanner scanUpToString:#"http" intoString:nil];
NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:#">"];
[scanner scanUpToCharactersFromSet:charset intoString:&urlString];
}
NSLog(#"%#", urlString);

Objective-C removing whitespace from strings in array

I want to import a file of strings line by line into an array. I want to get rid of all of the whitespace before and after the strings so that I can compare the strings a lot easier without having them not match due to small whitespace discrepancies. I NSData the content of the files then take the two strings
NSString* string = [[[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding] autorelease];
NSString* string2 = [[[NSString alloc] initWithBytes:[data2 bytes]
length:[data2 length]
encoding:NSUTF8StringEncoding] autorelease];
I tried below to remove the whitespace before adding to an array but it does not seem to work.
NSString *newString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSString *newString2 = [string2 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSArray *fileInput = [newString componentsSeparatedByString:#"\n"];
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
If you are looking at substituting all occurrences of whitespace then using stringByTrimmingCharactersInSet: won't help as it only trims off at the start and end of the string. You will need to use the stringByReplacingOccurrencesOfString:withString: method to eliminate the whitespace.
NSString * newString = [string stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString * newString2 = [string2 stringByReplacingOccurrencesOfString:#" " withString:#""];
However,
If you want to trim all the strings in the array then you will have to enumerate the array and add the trimmed strings in a new mutable array.
Looks to me like you are removing the white space from the front and back of the whole file but not from each line. Try something like this;
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
NSMutableArray *trimmedFileInput2 = [NSMutableArray array];
for(NSString *gak in fileInput2) {
[trimmedFileInput2 addObject:[gak stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
[Thanks #Deepak for the comment, dooh!]
Both #Deepak and #Bill Dudney being right, I'm just throwing in another way to solve your problem:
NSMutableArray *fileInput = [NSMutableArray array];
[string enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if ([line length] > 0) {
[fileInput addObject:
[line stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
}
}];
(Disclaimer: Works in iOS 4+, OS X 10.6+ only... but I love blocks! :))

Remove characters from NSString?

NSString *myString = #"A B C D E F G";
I want to remove the spaces, so the new string would be "ABCDEFG".
You could use:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.
All above will works fine. But the right method is this:
yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
It will work like a TRIM method. It will remove all front and back spaces.
Thanks
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
You can try this
- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:#" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
}
return str;
}
Hope this will help you out.