Compare, Getting string from a label - iphone

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];
}

Related

How to Multiply Two textfield values Without converting the text into integer or Number

I have two text fields and user entered the values. I can get the values of textFields like below
NSString *number1 = firstTextField.text;
NSString *number2 = secondTextField.text;
I want to multiply number1 and number2 without converting them into integer or number.I am doing like below
NSExpression *expression = [NSExpression expressionWithFormat:[NSString stringWithFormat:#"%#*%#",number1,number2]];NSLog(#"Multiplication result is----%#",[expression expressionValueWithObject:nil context:nil]);
I don't know if it is correct or not. If it is not correct please give me the suggestions how it can be possible.
By using NSExpression is one way to Multiply/Add/Subtract two number strings without converting them into integer or number.
NSExpression *expression = [NSExpression expressionWithFormat:expressionFormat];
You are using here expressionFormat as [NSString stringWithFormat:#"%#*%#",number1,number2];.
If you want to add or subtract number1 and number2 then replace * with + or -. In this way you have to proceed.
If the question was in an interview.
The interviewers were probably expecting you to write a method to go through both arrays and multiply the characters (converting one by one to integers) or (also identifying the represented character to know the equivalent integer number).
Searching on google there are some examples in different languages.
JAVA
http://csjobinterview.wordpress.com/2012/04/05/string-multiplication/
string multiplication
C++
Multiplying two number arrays
It is a common question in interviews.
I simply used textfields... and used the values that the user input into those textfields... here is one calculation example that has worked for me... in this example the user is trying to find the volume of beachstone they would need to order... the formula is pretty straight forward. Make sure you use the math brackets () to distinguish order of operations...
-(IBAction)calculate_beachstone:(id)sender {
float floatanswer =
([area1.text floatValue])+([area2.text floatValue])+([area3.text floatValue])+([area4.text floatValue])+([area5.text floatValue])+([area6.text floatValue])+([area7.text floatValue])+([area8.text floatValue])+([area9.text floatValue])+([area10.text floatValue]))
*([beachstone_depth.text floatValue])/12)/27);
NSString *stringRectResult=[[NSString alloc]
initWithFormat:#"%.1f",floatanswer];
answer_beachstone.text=stringRectResult;
}
I am adding the text found in the textfield (which user can only use numbers for input - custom keyboard)... in this example I have up to 10 fields which can be added together... then I use the * (multiply) to apply a depth in this example, and convert it back to a text string so I can display the result somewhere else...
In fact, if you write this part answer_beachstone to NSUserDefaults, you can use the result anywhere in different controllers, by calling it back.
If you're interested, here is how I did that...
-(IBAction)save_answer_beachstone:(id)sender {
save_answer_beachstone = [[NSString alloc] initWithString:answer_beachstone.text];
[answer_beachstone setText:save_answer_beachstone];
NSUserDefaults *save = [NSUserDefaults standardUserDefaults];
[save setObject:save_answer_beachstone forKey:#"save_answer_beachstone"];
}
Then I can use the resulting "answer" in any controller inside viewDidLoad...
[answer_beachstone setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"save_answer_beachstone"]];
I know the question was asked 4 years ago, but this formula syntax works for me in a number of ways, in various apps...
You can't multiply two strings. It's not possible.
For this you have to convert it into Integer or int using NSNumber or using:
[secondTextField.text intValue].
NSInteger number = [firstTextField.text integerValue]*[secondTextField.text integerValue];

Counting same letters in a word

I need to count same letters in a word. For example: apple is my word and first I found whether 'a' exists in this letter or not. After that I want to count the number of 'a' in that word but I couldn't do that. This is my code which finds the specific letter;
if([originalString rangeOfString:compareString].location==NSNotFound)
{
NSLog(#"Substring Not Found");
}
else
{
NSLog(#"Substring Found Successfully");
}
originalString is a word which I took from my database randomly. So, how to count?
Thanks for your help.
i have different idea let's try...
NSString *string = #"appple";
int times = [[string componentsSeparatedByString:#"p"] count]-1;
NSLog(#"Counted times: %i", times);
NSString *strComplete = #"Appleeeeeeeeeeeeeee Appleeeeeeeee Aplleeeeeeeeee";
NSString *stringToFind = #"e";
NSArray *arySearch = [strComplete componentsSeparatedByString:stringToFind];
int countTheOccurrences = [arySearch count] - 1;
Output :
countTheOccurrences --- 34
You could just loop over the string once, adding each letter to an NSMutableDictionary (as the key) and keeping a tally of how many times the letter occurs (as the value).
The resulting NSMutableDictionary would hold the number of occurences for each unique letter, whereby you can extract what you like.

Check if textfield text is almost equal to string

I have a UITextField called textfield. And I have this code to check if the text in the textfield is equal to "exampletext"
if ([textfield.text isEqualToString:#"exampletext"]) {
NSLog(#"Correct");
} else {
NSLog(#"Wrong");
}
But I also want to check if the text in the textfield is almost equal to "exampletext", if the text is almost the same as "exampletext". Like if the text was "eampletex" I want to NSLog(#"Close")
Are there any ways to check if the textfield text is like 50% equal to "exampletext"?
Or any ways to check if the textfield text has 50% the same characters as "exampletext"?
Or something else like that?
What you are looking for is an implementation of the levenshtein distance, levenshtein("hello", "hallo") => 1, levenshtein("hello", "ellos") => 2. You can check this library.
Once you have the distance between the two strings, you could get it as a percentage calculating: percentage = 100 * levenshtein(original,other) / length(original)
Here's my go at it. Create a custom character set from the string you want to match. Check each character in the texfield.text against that character set, and if the number of matches is close to the number of letters in the string, do something..
NSString *testString = #"wordToCompare";
NSString *textFromTextfield = textfield.text;
//create a custom character set from the word you want to compare to...
NSCharacterSet *characterSetForString = [NSCharacterSet characterSetWithCharactersInString:testString];
//keep track of how many matches...
int numberOfCharsThatMatchSet = 0;
for (int x = 0; x < [textFromTextField length]; x++) {
unichar charToCheck = [textFromTextField characterAtIndex:x];
if ([characterSetForString characterIsMember:charToCheck] == YES) {
numberOfCharsThatMatchSet++;
}
NSLog(#"%d", numberOfCharsThatMatchSet);
}
// if the number of matches is the same as the length of the word + or - 2...
if ((numberOfCharsThatMatchSet > [testString length] - 2 ) && (numberOfCharsThatMatchSet < [testString length] + 2 )) {
NSLog(#"close match...");
}
Not sure if this is 100% what you're looking for, but maybe it will help anyway...
I'm sure there might be some open source out there somewhere that would do this for you..however, one approach I can think of that will give you a bit of a lead...
Sort out the characters of both your strings into arrays. Determine which string you want to be the master string and grab the string length of it.
Now compare each character. Ex: Word 1: hello, Word 2: ello.
Each time a letter is found add one to a count. If by the end of your looping your count is 80% of the original length you grabbed from the master string or greater then you most likely have a partial match.
So for our example Word 1 will be our master string and its length is 5. "ello" contains 4/5 characters and therefore is matches 80% of the original string.
I don't think there is an easy way (with several lines of code) of solving this. There are several algorithms you might consider and pick the one which suits your needs most.
You should look at this question. Although it has been designed and answered for another language, you asked for a way or method so you have your solution there.

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