NSScanner Remove Substring Quotation from NSString - objective-c

I have NSString's in the form of Johnny likes "eating" apples. I want to remove the quotations from my strings so that.
Johnny likes "eating" apples
becomes
John likes apples
I've been playing with NSScanner to do the trick but I'm getting some crashes.
- (NSString*)clean:(NSString*) _string
{
NSString *string = nil;
NSScanner *scanner = [NSScanner scannerWithString:_string];
while ([scanner isAtEnd] == NO)
{
[scanner scanUpToString:#"\"" intoString:&string];
[scanner scanUpToString:#"\"" intoString:nil];
[scanner scanUpToString:#"." intoString:&string]; // picked . becuase it's not in the string, really just want rest of string scanned
}
return string;
}

This code is hacky, but seems to produce the output you want.
It was not tested with unexpected inputs (string not in the form described, nil string...), but should get you started.
- (NSString *)stringByStrippingQuottedSubstring:(NSString *) stringToClean
{
NSString *strippedString,
*strippedString2;
NSScanner *scanner = [NSScanner scannerWithString:stringToClean];
[scanner scanUpToString:#"\"" intoString:&strippedString]; // Getting first part of the string, up to the first quote
[scanner scanUpToString:#"\" " intoString:NULL]; // Scanning without caring about the quoted part of the string, up to the second quote
strippedString2 = [[scanner string] substringFromIndex:[scanner scanLocation]]; // Getting remainder of the string
// Having to trim the second part of the string
// (Cf. doc: "If stopString is present in the receiver, then on return the scan location is set to the beginning of that string.")
strippedString2 = [strippedString2 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\" "]];
return [strippedString stringByAppendingString:strippedString2];
}
I will come back (much) later to clean it, and drill into the documentation of the class NSScanner to figure what I am missing, and had to take care with a manual string trimming.

Related

Add 1 to a number in an NSString that contains characters Objective-C

I am new to learning Objective-C (my first programming language!) and trying to write a little program that will add 1 to a number contained within a string. E.g. AA1BB becomes AA2BB.
.
So far I have tried to extract the number and add 1. Then extract the letters and add everything back together in a new string. I have had some success but can't manage to get back to the original arrangement of the initial string.
The code I have so far gives a result of 2BB and disregards the characters before the number which is not what I am after (the result I am trying for with this example would be AA2BB). I can't figure out why!
NSString* aString = #"AA1BB";
NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"]; //Creating a set of Characters object//
NSScanner *theScanner = [NSScanner scannerWithString:aString];
int someNumbers = 0;
while (![theScanner isAtEnd]) {
// Remove Letters
[theScanner scanUpToCharactersFromSet:numberCharset
intoString:NULL];
if ([theScanner scanInt:&someNumbers]) {}
}
NSCharacterSet *letterCharset = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSScanner *letterScanner = [NSScanner scannerWithString:aString];
NSString* someLetters;
while (![letterScanner isAtEnd]) {
// Remove numbers
[letterScanner scanUpToCharactersFromSet:letterCharset
intoString:NULL];
if ([letterScanner scanCharactersFromSet:letterCharset intoString:&someLetters]) {}
}
++someNumbers; //adds +1 to the Number//
NSString *newString = [[NSString alloc]initWithFormat:#"%i%#", someNumbers, someLetters];
NSLog (#"String is now %#", newString);
This is an alternative solution with Regular Expression.
It finds the range of the integer (\\d+ is one or more digits), extracts it, increments it and replaces the value at the given range.
NSString* aString = #"AA1BB";
NSRange range = [aString rangeOfString:#"\\d+" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSInteger numericValue = [aString substringWithRange:range].integerValue;
numericValue++;
aString = [aString stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:#"%ld", numericValue]];
}
NSLog(#"%#", aString);

Search NSString for unknown string

In my iOS app I get the complete HTML of the website as an NSString. Further down along the line I need an NSString *pageTitle in the code. So, ideally, what I would like to do is search the NSString for <title>Title of page</title>.
I imagine what I need to do, is look for <title> then take the part after it up until </title>. However, I don't know how to do this properly. Any ideas?
This is what I have so far:
NSString *string = #"<html><head><title>Title of page</title></head><body></body></html>";
if ([string rangeOfString:#"<title>"].location == NSNotFound) {
NSLog(#"string does not contain a title");
} else {
NSLog(#"string contains a title!");
}
Whenever you need to do something like this NSScanner is the tool to use.
NSString *string = #"<html><head><title>Title of page</title></head><body></body></html>";
// Set up convenience variables for the start and end tag;
NSString *startTag = #"<title>";
NSString *endTag = #"</title>";
// Declare a string variable which will eventually contain the title
NSString *title;
// Create a scanner with the string you want to scan.
NSScanner *scanner = [NSScanner scannerWithString:string];
// Scan up to the <title>, throw away the result.
[scanner scanUpToString:startTag intoString:nil];
// Scan <title>, throw away the result.
[scanner scanString:startTag intoString:nil];
// Scan up to the </title> tag, put the characters into `title`
[scanner scanUpToString:endTag intoString:&title];
// Just to show that I'm not lying, print out the scanned title to the console.
NSLog(#"Title is: %#", title);
You can do this to get the title:
NSRange searchFromRange = [string rangeOfString:#"<title>"];
NSRange searchToRange = [string rangeOfString:#"</title>"];
NSString *title= [string substringWithRange:NSMakeRange(searchFromRange.location+searchFromRange.length, searchToRange.location-searchFromRange.location-searchFromRange.length)];
NSLog(#"title=%#",title);

filter starts with abc# and ends with # objective c

I'm new and this is my first post.
In my Inputstream I am getting list of message in where I have to filter a specific line and and to print that line, but some time its get crashed, can any one tell me where I'm making my mistake?
Here is my code:
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:#"&abc" intoString:nil]; //
NSString *substring = nil;
[scanner scanString:#"&abc" intoString:nil]; // Scan the # character
if([scanner scanUpToString:#"&" intoString:&substring]) {
// If the space immediately followed the &, this will be skipped
[substrings addObject:substring];
NSLog(#"substring is :%#",substring);
}
// do something with substrings
[substrings release];
I am getting:
&xyz;123:183:184:142&
&abc;134:534:435:432&
&qwe;323:535:234:532&
Sometimes I will get:
&qwe;323:535:234:532&
&abc;423:123:423:341&
&gfg;434:243:534:3434&
I want to print only string starts with "&abc" and ends with "&" ..
Is the code correct? Any suggestion?

Obj-C: Create Array From String Where items are in <>

I am trying to parse a String to an Array each item is between <> for example <this is column 1><this is column 2> etc....
Help would be much appreciated.
Thanks
Something to demonstrate:
NSString *string = #"<this is column 1><this is column 2>";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
NSString *temp;
while ([scanner isAtEnd] == NO)
{
// Disregard the result of the scanner because it returns NO if the
// "up to" string is the first one it encounters.
// You should still have this in case there are other characters
// between the right and left angle brackets.
(void) [scanner scanUpToString:#"<" intoString:NULL];
// Scan the left angle bracket to move the scanner location past it.
(void) [scanner scanString:#"<" intoString:NULL];
// Attempt to get the string.
BOOL success = [scanner scanUpToString:#">" intoString:&temp];
// Scan the right angle bracket to move the scanner location past it.
(void) [scanner scanString:#">" intoString:NULL];
if (success == YES)
{
[array addObject:temp];
}
}
NSLog(#"%#", array);
NSString *input =#"<one><two><three>";
NSString *strippedInput = [input stringByReplacingOccurencesOfString: #">" withString: #""]; //strips all > from input string
NSArray *array = [strippedInput componentsSeperatedByString:#"<"];
Note that [array objectAtIndex:0] will be an empty string ("") an this doesn't work of course, if one of the "actual" string contain < or >
One approach might be to use either componentsSeparatedByCharactersInSet or componentsSeparatedByString from NSString.
NSString *test = #"<one> <two> <three>";
NSArray *array1 = [test componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
NSArray *array2 = [test componentsSeparatedByString:#"<"];
You'll need to do some cleaning up afterward, either trimming in the case of array2 or removing white-space strings in the case of array1

Parsing Class writes last item twice

I am helpless. I parse this text...
<parse>HELLO</parse>
<parse>World</parse>
<parse>digit</parse>
<parse>wow</parse>
<parse>hellonewitem</parse>
<parse>lastitem</parse>
with an instance of NSScanner:
-(NSMutableArray *)parseTest
{
if (parserTest != NULL)
{
NSScanner *scanner = [[NSScanner alloc] initWithString:parserTest];
NSString *test;
NSMutableArray *someArray = [NSMutableArray array];
while ([scanner isAtEnd]!=YES)
{
[scanner scanUpToString:#"<parse>" intoString:nil];
[scanner scanString:#"<parse>" intoString:nil];
[scanner scanUpToString:#"</parse>" intoString:&test];
[scanner scanString:#"</parse>" intoString:nil];
[someArray addObject:test];
NSLog(#"%#",test);
}
return someArray;
}
Can't get my head around why I am getting the last object twice here in the returned array. What am I missing? Is there something wrong with the:
[scanner isAtEnd]!=Yes?
Thanks for any help!
Matthias
check the count of the someArray,
NSLog(#"%d",[someArray count]);
if it is 6, then you are doing something wrong in printing the values.
else if it is 7, then something going wrong somewhere, and need to be sorted
Hope the first condition is true.