How can i get parts of a String in Objective-C? - iphone

i would like to fetch a part of a string in objective C:
a sampletext:
This is the story of a startnew mountainend. There were many bluestart green houses end.........
the function should return a array of strings which are all in between the "start" and the "end".
How can i write this in objective C?
Andreas

I think what you want is something like this.
NSString *text = nil;
NSScanner *theScanner = [NSScanner scannerWithString:#"This is the story of a startnew mountainend. There were many bluestart green houses end"];
[theScanner scanUpToString:#"start" intoString:NULL] ;
[theScanner scanUpToString:#"end" intoString:&text] ;
Of course there are several edge cases you should watch out for like what if you reach the end of the string without find "end"? What if there is a "start" after you already found the word "start" before you find an "end"? Anyways, hopefully this points you in the right direction.

Related

How to display string that contain HTML tags in it as plain text [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove HTML Tags from an NSString on the iPhone
I am using google direction api to display map in my mapview and it gives me HTML direction string ,that contain HTML tags.
Now i want to display that string in plain text how can i do that.My strings are here :
Head <b>southwest</b> toward <b>GH Rd</b>
Exit the roundabout onto <b>GH Rd</b><div style="font-size:0.9em">Go through 1 roundabout</div>
At the roundabout, take the <b>1st</b> exit onto <b>Road Number 2</b><div style="font-size:0.9em">Pass by myonlinesearch.blogspot.com (on the left in 600 m)</div>
At the roundabout, take the <b>3rd</b> exit onto <b>CH Rd</b>
At <b>Indroda Cir</b>, take the <b>2nd</b> exit onto <b>Gandhinagar Ahmedabad Rd/SH 71</b><div style="font-size:0.9em">Continue to follow Gandhinagar Ahmedabad Rd</div><div style="font-size:0.9em">Go through 1 roundabout</div>
At the roundabout, take the <b>1st</b> exit onto <b>Sardar Patel Ring Rd</b>
At <b>Ranasan Cir</b>, take the <b>3rd</b> exit onto <b>NH 8</b><div style="font-size:0.9em">Pass by Galaxy Restaurant (on the left in 4.3 km)</div>
Turn <b>left</b> onto <b>Galaxy Rd</b><div style="font-size:0.9em">Pass by Shiv Shakti Food Fort (on the left)</div>
Turn <b>left</b> onto <b>NH 59</b>
Turn <b>right</b><div style="font-size:0.9em">Go through 1 roundabout</div>
Turn <b>right</b>
Turn <b>left</b><div style="font-size:0.9em">Destination will be on the right</div>
You can use RegularExpression/Predicates to remove all characters between < & >.
But if your text contains some <> it will be removed
NSRange range;
NSString *string;
while ((range = [string rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound){
string=[string stringByReplacingCharactersInRange:range withString:#""];
}
NSLog(#"Un block string : %#",string);
You will have to parse the text via a parser it is very easy to parse these text just scan the line and use replace function there.
[yourString stringByReplacingOccurrencesOfString:#"<b>"withString:""];
[yourString stringByReplacingOccurrencesOfString:#"</b>"withString:""];
This will do the trick for you.
Either you can go with..
-(NSString *) stringByStrippingHTML
{
NSRange r;
NSString *s = [[self copy] autorelease];
while ((r = [s rangeOfString:#"]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:#""];
return s;
}
Or better use NSString category to remove HTML from your string i.e. "GTMNSStringHTMLAdditions".

Compare, Getting string from a label

I'm making a word game and I've finally come up to one of the most important parts of my game, the compare part.
I got this label which will be invisible when it launches with the word that has to be guessed displaying in it with a random word generator. For example the word is: GARAGE
Now, for my game I have to compare the word with the input now I've already done this with the entire word with NSString but I want it to compare every letter. I want to be able to show that if the input has G as the first letter aswell, like garage. I want it to do something.
I want to know if this is possible and which methods you would use. I was thinking about making 6 strings since all my random words have 6 letters, and then break the word to 6 strings and the input aswell and then compare strings?
Hope someone has some usefull tips or example code thanks
So, assuming your string to be guessed...
NSString *stringToGuess = #"GARAGE";
and you were checking to see if it started with "GA"
NSString *myString = #"GA";
you would check it with hasPrefix:
if ([stringToGuess hasPrefix:myString]) {
// <stringToGuess> starts with <myString>
}
The documentation for NSString describes lots of neat methods for just about anything string related.
hasPrefix will let you tell if one string begins with another string. There's also characterAtIndex. You could use that to get one character from each string and compare it to the other.
You could write a method that would take an integer index and compare the two strings at that index:
- (BOOL) compareStringOne: (NSString *) stringOne
toStringTwo: (NSString *) stringTwo
atIndex: (NSUInteger) index;
{
if ([stringOne length] < index+1 || [stringTwo length] < index+1)
return FALSE;
return [stringOne characterAtIndex: index] == [stringTwo characterAtIndex: index];
}

iOS iPhone how to list all keywords in a UTextView by frequency of use?

I got a UITextView with an arbitrary length text (up to 10000 characters). I need to parse this text, extract all keywords and list them by the frequency of use with the most frequently used word being on top, next one down, etc. I will most likely present a modal UITableView after the operation is completed.
I'm thinking of an efficient and useful way to do this. I can try to separate a string using a delimiter in the form of [whitespace, punctuation marks, etc].
This gets me an array of character sequences.
I can add each add sequence as an NSMutableDictionary key, and increment its count once I see another instance of that word. However, this may result in a list of 300-400 words, most having frequency of 1.
Is there a good way to implement the logic that I'm describing? Should I try to sort the array in alphabetical order and try some kind of "fuzzy" logic match? Are there any NSDataDetector or NSString methods that can do this kind of work for me?
An additional question is: how would I extract stuff like a, at, to, for, etc, and do not list them in my keyword list?
It would be great if I can take a look at a sample project that has already accomplished this task.
Thank you!
You can use CFStringTokenizer to get the word boundaries. For counting, you could use an NSMutableDictionary, as you suggested, or an NSCountedSet, which might be slightly more efficient.
If you're not interested in words that have a frequency of 1 (or some other threshold), you would have to filter them out after counting all the words.
For ignoring certain words (a, the, for...), you need a word list specific to the language of your text. The Wikipedia article on stop words contains a couple of links, e.g. this CSV file.
There are many approaches to do this.
You should definitely add all your Keywords to an array (or other collection object) and reference it/ iterate through it so you are searching for these keywords and only these keywords (and are avoiding checking for occurrences of a, at, to, for, etc.)
NSArray *keywords = [ add your keywords ];
NSString *textToSearchThrough = #" your text "; // or load your text File here
- loop control statement here (like maybe fast enumerate), and inside this loop:
NSRange range = [textToCheckThrough rangeOfString:keywords[currentKeyword]
options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound) {
// meaning, you did find it
// add it to a resultsArray, add 1 to this keyword's occurrenceCounter (which you must also declare and keep track of)
// etc.
}
Then you loop through your results array, check number of occurrences per keyword, purge those who's occurrence count is < minOccurrenceCount, and sort remaining from highest to lowest.
I ended up going with the CFStringTokenizer . I'm not sure if the bridged casts below are correct, but it seems to work
-(void)listAllKeywordsInString:(NSString*)text
{
if(text!=nil)
{
NSMutableDictionary* keywordsDictionary = [[NSMutableDictionary alloc] initWithCapacity:1024];
NSString* key = nil;
NSLog(#"%#",text);
NSLog(#"Started parsing: %#",[[NSDate date] description]);
CFStringRef string =(__bridge CFStringRef)text; // Get string from somewhere
CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, (__bridge_retained CFStringRef) text, CFRangeMake (0,CFStringGetLength((__bridge_retained CFStringRef)text)), kCFStringTokenizerUnitWord, CFLocaleCopyCurrent());
unsigned tokensFound = 0; // or the desired number of tokens
CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
while(kCFStringTokenizerTokenNone != (tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)) ) {
CFRange tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
CFStringRef tokenValue = CFStringCreateWithSubstring(kCFAllocatorDefault, string, tokenRange);
// This is the found word
key =(__bridge NSString*)tokenValue;
//increment its count
NSNumber* count = [keywordsDictionary objectForKey:key];
if(count!=nil)
{
[keywordsDictionary setValue:[NSNumber numberWithInt:1] forKey:key];
}else {
[keywordsDictionary setValue:[NSNumber numberWithInt:count.intValue+1] forKey:key];
}
CFRelease(tokenValue);
++tokensFound;
}
NSLog(#"Ended parsing. tokens Found: %d, %#",tokensFound,[[NSDate date] description]);
NSLog(#"%#",[keywordsDictionary description]);
// Clean up
CFRelease(tokenizer);
}
}

how to display the first word in the search table in the iphone app

hii every one in my iphone app i have a search screen & i have some entries in the search bar like sudha, tharanga and womens era (some magazines ) suppose if we search cricket special, it has to show the respective magazine
so i planned to have the table view data like follows
sudha (cricket special, anna hazare special)
tharanga (footbal special,x special)
womens era (some y special)
and while loading data to the table view by trimming the all data which is present between the brackets ( ) and should i display remaining in the table view
so how can i trim the string in such a way that it should remove the data with in brackets and bracket symbols
so that my table view data should become like this
sudha
tharanga
womens era
, thanx in advance
Regarding trimming the string as per your requirement, I guess the simplest way to go about it is to use the - (NSArray *)componentsSeparatedByString:(NSString *)separator method as follows;
NSArray *anArray = [theFullString componentsSeparatedByString:#"("];
Assuming theFullString = #"womens era (some y special)", the resulting arrays first element would be as #"womens era ". I assume this works fine.
Use this nnstring method to get the desired result,
- (NSString *)substringWithRange:(NSRange)range;
OR you can do that, first find bracket location,
int pointPos = -1;
for(int i=0; i<= [myString length]-1; i++){
if ([myString characterAtIndex:i] == '(') {
pointPos = i;
break;
}
}
NSString *finalString = [myString substringToIndex:pointPos];

Parsing string in sections with NSScanner

I am trying to parse a string with a format like this:
*date1:
- band1.1 # venue1.1.
- band1.2 # venue1.2.
*date2:
- band 2.1 # venue2.1.
- band 2.2 # venue2.2.
etc
The number of dates and the number of bands and the associated venue can vary. I am using code based on the example at the bottom of this page.
I am using this snippet of code (I left out the bits at the bottom as they are irrelevant, but yes, I do close the loops etc.):
NSScanner *scanner1 = [NSScanner scannerWithString:contents];
NSCharacterSet *colon = [NSCharacterSet characterSetWithCharactersInString:#":"];
NSCharacterSet *at = [NSCharacterSet characterSetWithCharactersInString:#"#"];
NSCharacterSet *dot = [NSCharacterSet characterSetWithCharactersInString:#"."];
NSLog(#"scanner starting");
while ([scanner1 isAtEnd] == NO) {
if ([scanner1 scanString:#"*" intoString:NULL] && [scanner1 scanUpToCharactersFromSet:colon intoString:&tempDate] && [scanner1 scanString:#":" intoString:NULL])
{
NSLog(#"%#", tempDate);
if ([scanner1 scanString:#"-" intoString:NULL] && [scanner1 scanUpToCharactersFromSet:at intoString:&tempBands] && [scanner1 scanString:#"#" intoString:NULL] && [scanner1 scanUpToCharactersFromSet:dot intoString:&tempVenue]
&&[scanner1 scanString:#"." intoString:NULL])
{
NSLog(#"%# %#", tempBands, tempVenue);
}
}
} NSLog(#"ended scanning");
Currently, the first date is parsed and printed to the console, and the first venue and band of that date are printed. "ended scanning" is never printed. I have been battling this for hours and I am unsure of what to do now. I have a feeling that I do not understand the inner workings of NSScanner and there is probably a different way to tackle this problem. Maybe I need a second scanner?
After the first round of the while loop, the scanner's position is right after "venue1.". The next round of the loop starts with scanning an asterisk, which fails (returns NO) because the next (non-whitespace) character is a dash. Therefore, the body of the if statement isn't executed and the scanner's position is not advanced any further, resulting in an infinite loop.