Getting multiple tags from html source code in Objective-C - ios

I have extracted the source code from a website but i would like to display the strings of three urls. I have managed to strip the code so the only url's are the ones I need. How can I get the three strings in an array. The URL's look like this: Example
where I need to extract the string: 'example'
I have tried the NSScanner but without any luck. Please advice

Not the most clever way, but you can get the first approach of > and then the first < from there. All with standard NSString methods like rangeOfString: and such.

This code with NSScanner should give you luck :)
-(NSMutableArray *)yourStringArrayWithHTMLSourceString:(NSString *)html {
NSString *from = #"<a href=\"";
NSString *to = #"</a>";
NSMutableArray *array = [[NSMutableArray alloc]init];
NSScanner* scanner = [NSScanner scannerWithString:html];
for(int x=0;x<3;x++) {//You said only 3 strings
NSString *tempString;
[scanner scanUpToString:from intoString:nil];
[scanner scanString:from intoString:nil];
[scanner scanUpToString:to intoString:&tempString];
NSString *str = [tempString substringFromIndex:[tempString rangeOfString:#"\">"].location+2];
[array addObject:str];
}
return array;
}
usage:
for example:
NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://facebook.com"] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",[self yourStringArrayWithHTMLSourceString:html]);//will return NSMutableArray
Here is how to convert NSMutableArray to NSArray if you would like to to that:
NSArray *array = [NSArray arrayWithArray:mutableArray];

Related

Incompatible pointer types NSString and NSArray why?

-(void)displayData:(NSString *)text{
NSLog(#"DATA SEND");
NSString *string1 = [NSString stringWithFormat:text];
NSString *separate = [string1 componentsSeparatedByString:#"B"];
separate is the one that gives issue? How do I properly do this? I'm trying to perform a string split.
componentsSeparatedByString: method returns NSArray not NSString, try that:
NSArray *seperate = [string1 componentsSeparatedByString:#"B"];
what is that?
NSString *string1 = [NSString stringWithFormat:text];
Right way
NSString *string1 = [NSString stringWithFormat:#"%#",text];
or
NSString *string1 = [NSString stringWithString:text];
and then Grag answer.

Extract substring from a string in iOS?

Is there any way to extract substring from a string like below
My real string is "NS09A" or "AB455A" but i want only "NS09" or "AB455" (upto the end of numeric part of original string).
How can i extract this?
I saw google search answers like using position of starting and endinf part of substring we can extract that ,But here any combination of "Alphabets+number+alphabets" .I need only " "Alphabets+number"
Perhaps not everybody will agree, but I like regular expressions. They allow to specify
precisely what you are looking for:
NSString *string = #"AB455A";
// One or more "word characters", followed by one or more "digits":
NSString *pattern = #"\\w+\\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string
options:NSMatchingAnchored
range:NSMakeRange(0, [string length])];
if (match != nil) {
NSString *extracted = [string substringWithRange:[match range]];
NSLog(#"%#", extracted);
// Output: AB455
} else {
// Input string is not of the expected form.
}
Try This:-
NSString *str=#"ASRF12353FYTEW";
NSString *resultStr;
for(int i=0;i<[str length];i++){
NSString *character = [str substringFromIndex: [str length] - i];
if([character intValue]){
resultStr=[str substringToIndex:[str length]-i+1];
break;
}
}
NSLog(#"RESUKT STRING %#",resultStr);
I tested this code:
NSString *originalString = #"NS09A";
// Intermediate
NSString *numberString;
NSString *numberString1;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
[scanner scanUpToCharactersFromSet:numbers intoString:&numberString];
[scanner scanCharactersFromSet:numbers intoString:&numberString1];
NSString *result=[NSString stringWithFormat:#"%#%#",numberString,numberString1];
NSLog(#"Finally ==%#",result);
Hope it Help You
OUTPUT
Finally ==NS09
UPDATE:
NSString *originalString = #"kirtimali#gmail.com";
NSString *result;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *cs1 = [NSCharacterSet characterSetWithCharactersInString:#"#"];
[scanner scanUpToCharactersFromSet:cs1 intoString:&result];
NSLog(#"Finally ==%#",result);
output:
Finally ==kirtimali
Use NSScanner and the scanUpToCharactersFromSet:intoString: method to specify which characters should be used to stop the parsing. This could be in a loop with some logic or it could be applied in conjunction with setScanLocation: if you already have a method of finding the start of each section you want to extract.
When using scanUpToCharactersFromSet:intoString: you are looking for the next invalid character. It doesn't need to be a 'special' character (in a unicode sense), just a known set of characters that aren't valid for the content you want. So, you might use:
[[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet]
You can use - (NSString *)substringWithRange:(NSRange)aRange method on NSString class to get a substring extracted. Use NSMakeRange to create the NSRange object.

How to concatenate TextView.text

I have two UITextViews:
self.itemsTextView.text;
self.priceTextView.text;
I want to concatenate these two like so:
NSString *data = self.textView.text + self.itemsTextView.text;
I have tried using a colon, as suggested by this thread, but it doesn't work.
NSString *data = [self.textView.text : self.itemsTextView.text];
For concatenating you have several options :
Using stringWithFormat:
NSString *dataString =[NSString stringWithFormat:#"%#%#",self.textView.text, self.itemsTextView.text];
Using stringByAppendingString:
NSMutableString has appendString:
You may use
NSString * data = [NSString stringWithFormat:#"%#%#",self.textView.text,self.itemsTextView.text];
There are so many ways to do this. In addition to the stringWithFormat: approaches of the other answers you can do (where a and b are other strings):
NSString *c = [a stringByAppendingString:b];
or
NSMutableString *c = [a mutableCopy];
[c appendString b];

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

iOS Read file lines into array

I have a file containing a couple thousands words on individual lines. I need to load all of these words into separate elements inside an array so first word will be Array[0], second will be Array[1] etc.
I found some sample code elsewhere but Xcode 4.3 says it's using depreciated calls.
NSString *tmp;
NSArray *lines;
lines = [[NSString stringWithContentsOfFile:#"testFileReadLines.txt"]
componentsSeparatedByString:#"\n"];
NSEnumerator *nse = [lines objectEnumerator];
while(tmp = [nse nextObject]) {
NSLog(#"%#", tmp);
}
Yes, + (id)stringWithContentsOfFile:(NSString *)path has been deprecated.
See Apple's documentation for NSString
Instead use + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
Use as follows:
lines = [[NSString stringWithContentsOfFile:#"testFileReadLines.txt"
encoding:NSUTF8StringEncoding
error:nil]
componentsSeparatedByString:#"\n"];
Update: - Thanks to JohnK
NSCharacterSet *newlineCharSet = [NSCharacterSet newlineCharacterSet];
NSString* fileContents = [NSString stringWithContentsOfFile:#"testFileReadLines.txt"
encoding:NSUTF8StringEncoding
error:nil];
NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:newlineCharSet];
Check this. You might have to use an updated method.

Resources