Objective C - Adding characters at specific parts of a string - iphone

I have made a quadratic equation solver for the iPhone and when the text box is clicked, my own custom keypad appears. I have a button that changes whether the number is positive or negative. Right now I what happens is that when the button is pressed (0 - current value of text) is what is displayed in the text box, so if the number is positive, it will become negative and if it is negative it will become positive. I am having some problems doing this so what I wanted to is to put a minus sign at the beginning of the string if the number is positive and if the number is negative, the minus sign will be removed. Can anyone give me guidance on this?

Instead of negating using a mathematical function I assigned a NSMutableString to my UITextField then I inserted a "-" sign using insertString:atIndex: then I reassigned the changed string to my UITextField. To toggle between positive and negative, I created an if function so if the float value of my textfield is greater or equal to 0, then an "-" is inserted but if the float value of my text field is less than zero, the "-" is removed using deleteCharactersInRange. Here is my code as it stands:
- (IBAction)positivity{
NSMutableString *a = [NSMutableString stringWithString:aVal.text];
if([aVal.text floatValue]>=0){
[a insertString: #"-" atIndex: 0];
aVal.text = a;
}
else if([aVal.text floatValue]<0){
NSRange range = {0,1};
[a deleteCharactersInRange:range];
aVal.text = a;
}
}
aVal is the name of the UITextField that i am changing.

An alternative to the straight string approach is to not use a string. A while back I wrote a graphing calculator for iPhone that stored the equation internally in an NSMutableArray of NSStrings. Each slot in the array corresponded to one element in the equation, such as "x", "^", "sin(", etc.
When I needed to negate the equation, it was much easier to tell the array to insertObject:#"-" atIndex:0 than to try and insert it directly into the string. Then whenever the array was changed, I just remade the equation string like this:
NSString * newEquation = [equationElements componentsJoinedByString:#""];

While you could directly manipulate a string representation of a numeric value, such an approach is a bad idea. Not only is it less efficient than other alternatives, but potentially incorrect. (For example, #Ken's answer would result in two minus signs.)
What you probably want to do is negate the numeric value (just multiply it by -1, or subtract it from 0 as you suggested) and reflect that change in the interface (you mention a text box).
If you're using standard Cocoa controls (which inherit from NSControl, as NSTextField does) I suggest using -[NSControl setIntegerValue:] to change the text of the text field. If you (can) break up your UI well and have a text field for each variable in the quadratic equation, this should be fairly simple. (If you're using something other than an integer value, use something like -setDoubleValue: or -setFloatValue: instead.)
If you must create your own string beforehand, using an integer format specifier will display a "-" sign automatically if appropriate. Be sure to use %ld instead of %d (thanks, #Peter!) as the format specifier for NSInteger values to avoid possibly truncating values larger than 32-bit. For example:
NSString *result = [NSString stringWithFormat:#"%ld", nsIntegerValue];
In a more general sense, if you need to insert a dynamically-obtained string (not just something for which you can create a format string at compile time) you can also use an NSMutableString and its methods -appendString: and -insertString:atIndex: as well.

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

Double being displayed with unnecessary zeros after decimal

In my calculator app, I am trying to display a "double" value in a UILabel. However, the value always has more zeros than it needs. For example, 64 is displayed as 64.000000, 4.23 is displayed as 4.230000, etc.
How can I make it display only as many decimal places as fits?
vector<Token> postfix; // create empty postfix vector
infixToPostfix(infix, postfix); // call inToPost to fill up postfix vector from infix vector
answer = postFixEvaluate(postfix); // evaluate expression
expString.clear();
expNSString = [NSString stringWithFormat:#"%f", answer]; // convert "answer" to NSString
displayScreen.text = expNSString; // display answer in UIlabel "displayScreen"
As mentioned in the [NSString stringWithFormat:] class reference:
Parameters
format A format string. See “Formatting String Objects” for
examples of how to use this method, and “String Format Specifiers” for
a list of format specifiers. This value must not be nil.
and following the first link, one of the first examples is:
NSString *string1 = [NSString stringWithFormat:#"A string: %#, a float: %1.2f",
#"string", 31415.9265]; // ^
// string1 is "A string: string, a float: 31415.93"
You need to learn to think for yourself. Read the documentation!
This question is a little old, but did you try %g? This will produce scientific notation in some cases:
64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
But, as it says, you can control this to some extent using the precision field: if your numbers are large, you will need to increase the precision to avoid scientific notation. If your numbers are small, then I think there is nothing you can do about it when using %g.
I get this output:
64.0 -> "64"
64.1 -> "64.1"
64.15555 -> "64.1556" // default precision is 6

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.

Drawing one NSString in multiple rects

I have a really long string, with thousands of line with a default font. So rather than draw the whole thing out in one table view cell, I'm going to make several cells to draw the same string, each drawing the next part of the string.
I'm having a hard time finding a starting point. Say I draw the first 500 pixels of height of the string in the rect - how do I know where to start in my second rect? If it's the same string, how can I specify for it to draw only some parts of the string?
Each cell will know it's own row number, so I'll be able to determine where exactly in the table I am, I just don't know how the string will know which part it's supposed to draw..
Or another question would be: how can I break up one string into multiple strings based on a certain number of lines?
Edit: Here are some NSString methods I'm finding that might be useful, but I still don't know how I would use them in my case:
- (void)getLineStart:(NSUInteger *)startIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange
- (NSRange)lineRangeForRange:(NSRange)aRange
Use substringWithRange: This will allow you to select a start and end point of the string. I would grab each section by a number of characters. So section 1 would be 0-500 section 2 would be 500-1000. The problem here would be you may cut off in the middle of a sentence. You can use something like lineRangeForRange to determine your ranges for the substring.
lineRangeForRange
Returns the range of characters representing the line or lines containing a given range.
- (NSRange)lineRangeForRange:(NSRange)aRange
Parameters
aRange
A range within the receiver.
Return Value
The range of characters representing the line or lines containing aRange, including the line termination characters.
EDIT
NSString *string = #"tjykluytjghklukytgjhkkghkj sdkjlhfkjsadgfiulgeje fuaeyfkjasdgfueghf aksjgflkj. wyruehskjluishfoeifh uasyeajhkfa uiyelkjahsdf uayekljshdf aehkfjsd. \n I iheio;fajkdsf sdfhlueshkfjskdhf ujhelkjfh. luehljkfhlsdf. leufhlkjdshfa. \n euoiywhfldsjkhf euyhfsdlkj. ewhlkjfsd. euilhfsdkjishdkjf euhjklsfd. \n";
NSLog(#"string length:%i", [string length]);
NSRange range;
range.length = [string length]/2;
range.location = 0;
NSLog(#"LineRangeForRange:%i", [string lineRangeForRange:range].length);
NSLog(#"Substring:%#", [string substringWithRange:[string lineRangeForRange:range]]);
Log displays:
string length:295
LineRangeForRange:148
Substring:tjykluytjghklukytgjhkkghkj sdkjlhfkjsadgfiulgeje fuaeyfkjasdgfueghf aksjgflkj. wyruehskjluishfoeifh uasyeajhkfa uiyelkjahsdf uayekljshdf aehkfjsd.
So what this did was I supplied LineRangeForRange a range which was from zero to half of the string. It could the last end line "\n" with in that range. Then I grabbed that substring
Doesn't sound like a way I would wanna read text in an app. Why not use a textView?
Edit: my recommendation wasn't to put a textView in a tableViewCell but to display the beginning of the text truncated and on click push a viewControllers that displays a textView. Kind of like Mail does.

doubleValue does not convert the object to a double value correctly at all times

I have an NSArray in which I would like to store double values. I defined it as follow
NSMutableArray *setOfDoubles;
I add the elements as follow
NSNumber *num;
num = [NSNumber numberWithDouble:someDouble];
[setOfDoubles addObject:num];
And I read the element as follow
num = [setOfDoubles lastObject];
[setOfDoubles removeLastObject];
doubleValueToUse = [num doubleValue];
My problem is sometimes (Not always), for example when num (as an object) is 5.1, doubleValueToUse (as a double value) is 5.099999999999996. The way I figured num (as an object) is 5.1 is that I debug and when I am hovering the mouse on top of num on the line num = [setOfDoubles lastObject]; it shows 5.1 but after doubleValue conversion it becomes the number I mentioned. Does anybody know why is this happening?
Not every number can be accurately represented using a float variable. For example, you can't precisely represent, say, 1/3 using a finite number of digits in our common decimal (base-10) system, but in ternary (base-3), it would be just 0.1. Similarly, the numbers you can write with a finite number of digits in decimal, may not necessarily have the finite number of digits in their binary representation, hence the error.
A few links on the topic if you are interested:
http://floating-point-gui.de/basic/
http://www.mathworks.com/support/tech-notes/1100/1108.html
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
This is normal for float values.
If you want to save initial (same) representation of float numbers in all places of your code, you can save them, for example, in NSString. When you will need float number you will just write [NSString floatValue];. But it is not effective if you have large amount of float values.