Objective C - Number to String and Grab length inconsistencies - objective-c

I am trying to grab a number from a text box entry, convert it to string and grab the length of it. (IE: Perform a LEN(someInteger) on a number).
I have been able to get it working, however there are some inconsistencies when the number is 0 or null.
For example;
-(IBAction)update
{
// inputField is the number pad textbox
double myInput = [inputField.text doubleValue];
//
NSNumber *c = [NSNumber numberWithDouble:myInput];
NSString *myOutput = [c stringValue];
NSLog(#"Starting number (number) = %#", c);
NSLog(#"myOutput (string) = %#", myOutput);
NSLog(#"myOutput (length) = %d", ([myOutput length]) );
}
The conversion for number to string works fine. The problem I have is with the length, especially when there are no numbers (or null) entry.
I have a number pad text box entry on an XIB which has a "text" of 0 (the placeholder just says "Enter number here")
When you first start typing into the text box the "text" goes away and you start with a blank text box.
Problem 1 -- when you first enter the text box there is nothing in the textbox, but my NSLog says the output length is 1 character long.
This causes a problem because visually there is nothing in the textbox but the [myOutput length] reports 1 character length.
Problem 2 -- when you start to enter numbers, everything goes well -- but when you start to remove numbers to the point where you clear the text box completely it reports a length of 1 character.
How can it read 1 character long if there is nothing in the text box? I think it must be the "text" (From identity inspector) again.
Summary.
There is a number pad text box entry field. Whenever you update the entry, it calls the IBaction update method.
When you first enter numbers into the text box there is nothing visually displayed in the input field, but the NSLog reports the length is 1 character long.
When you start entering numbers and then start to remove them one at a time till you completely remove all numbers it reports the length as being 1 character long.
In both cases the NSLog should be reporting 0 length, but it never does. I tried doing [myOutput length] - 1 but this gives me weird results.
Any help on this would be great
Thanks.

If there's no text, myInput will be equal to 0.0. myOutput will then be equal to #"0", which has a length of 1.
Why not just use [inputField.text length]?
You could do something like this:
NSNumber *number = nil;
if ([inputField.text length] > 0) {
number = [NSNumber numberWithDouble:[inputField.text doubleValue]];
}
That way you have your number if it exists, otherwise number will be nil.

Related

Objective-c - get count elements of an array

I'm an Objective-C rookie, and I want to get the elements count of an array of chars. I managed to find only this way:
#autoreleasepool {
char parola[30];
int c;
NSLog(#"Write word:");
scanf("%c",&parola[30]);
c = sizeof(parola)/sizeof(parola[0]);
NSLog(#"The word has %i letters",c);
}
return 0;
The problem is that it gives me the length I specified in the array declaration, not the elements count.
Any idea?
You have a few errors there.
You want the user to input a "word", i.e. a string. Then don't use %c, which only scans one character, but %s instead, which scans one string (note that that can mean that the user also enters spaces, or more than 29 characters).
You store beyond the array. The array is declared as
char parola[30];
That means it can be indexed with values 0 .. 29. But your &parola[30] points beyond the array (at index 30, which does not "exist"). That is not what you want. Do this:
scanf("%s", parola);
And hope that the user doesn't enter more than 29 characters.
The length of the string can then be found using
c = strlen(parola);
So this becomes:
#autoreleasepool {
char parola[30];
unsigned long c;
NSLog(#"Write word:");
scanf("%s", parola);
c = strlen(parola);
NSLog(#"The word has %ld letters", c);
}
return 0;
Instead of NSLog, you can also use printf:
printf("Write word: ");
and
printf("The word has %ld letters\n", c);
That will look cleaner, as NSLog() always shows these extra infos, like
2017-06-04 12:37:25.758802+0200 SOTest[4718:2690388]
And that is, IMO, plain ugly. Good for a log, but not good for clean screen output. The output now becomes:
Write word: Tesla
The word has 5 letters
Program ended with exit code: 0

Objective-C, correctly separate columns in CSV by comma

I have an Excel file that I exported as a CSV file.
Some of the data in the columns also have commas. CSV escapes these by putting the string in the column in quotes (""). However, when I try to parse it in Objective-C, the comma inside the string seperates the data, as if it were a new column.
Here's what I have:
self.csvData = [NSString stringWithContentsOfURL:file encoding:NSASCIIStringEncoding error:&error];
//This is what the data looks like:
//"123 Testing (Sesame Street, Testing)",Hello World,Foo,Bar
//Get rows
NSArray *lines = [self.csvData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//Get columns
NSArray *columns = [[lines objectAtIndex:0] componentsSeparatedByString:#","];
//Show columns
for (NSString *column in columns) {
NSLog(#"%#", column);
}
//Console shows this:
"123 Testing (Sesame Street
Testing)"
Hello World
Foo
Bar
Notice how "123 Testing (Sesame Street and Testing)" are output as separate columns. I need these to be one. Any ideas?
Any ideas?
Design an algorithm.
At the start of the input you have one of three possibilities:
You have a " - parse a quoted field
You have a , - handle an empty field
Otherwise - parse a non-quoted field
After parsing if there is any more input left then iterate (loop).
You might start with some variables:
NSUInteger position = 0; // current position
NSUInteger remaining = csvData.length; // left to parse
then enter your loop:
while(remaining > 0)
{
get the next character:
unichar nextChar = [csvData characterAtIndex:position];
Now check if that character is a ", , or something else. You can use an if or a switch.
Let's say it's a comma, then you want to find the position of the next comma. The NSString method rangeOfString:options:range will give you that. The last argument to this method is a range specifying in which part of the string to search for the comma. You can construct that range using NSMakeRange and values derived from position and remaining.
Once you have the next comma you need to extract the field, the substringWithRange: method can get you that.
Finally update position and remaining as required and you are ready for the next iteration.
You'll have to handle a few error cases - e.g. opening quote with no closing quote. Overall it is straight forward.
If you start down this path and it doesn't work ask a new question, showing your code and explaining where you got stuck.
HTH

Count number of arbitrary repeating decimal numbers in NSString

In my code, I'm dealing with an NSString that contains an NSNumber value. This NSNumber value could possibly be a repeating decimal number (e.x. 2.333333333e+06) that shortens to "2.333333" in a string format. It could also be a terminating number (e.x. 2.5), negative, or irrational number (2.398571892858...) (only dealing with decimals here)
I need to have a way to figure out if there are the repeating numbers in the string (or the NSNumber, if necessary). In my code, I would have no way to know what the repeating number would be, as it's a result of computations started by the user. I have tried this for loop (see below) that doesn't work the way I want it to, due to my inexperience with string indexing/ranges/lengths.
BOOL repeat = NO; //bool to check if repeating #
double repNum, tempNum; //run in for loop
NSString *repeating = [numVal stringValue]; //string that holds possible repeating #
for (int i = 3; i <= [repeating length]-3; i++) { //not sure about index/length here
if (i == 3) {
repNum = [repeating characterAtIndex:i];
}
tempNum = [repeating characterAtIndex:i];
if (tempNum == repNum) {
repeat = YES;
} else {
repeat = NO;
}
}
This code doesn't work as I'd like it to, mainly because I also have to account for negative dashes in the string and different amounts of numbers (13 1/3 vs. 1 1/3). I've used the modffunction to separate the integers from the decimals, but that hasn't worked well for me either.
Thank you in advance. Please let me know if I can clarify anything.
EDIT:
This code works with the finding of different solutions for polynomials (quadratic formula). Hope this helps put it into context. See here. (Example input)
NSNumber *firstPlusSolution, *secondMinusSolution;
NSString *pValueStr, *mValueStr;
firstPlusSolution = -(b) + sqrt(square(b) - (4)*(a)*(c)); //a, b, c: "user" provided
firstPlusSolution /= 2*(a);
secondMinusSolution = -(b) - sqrt(square(b) - 4*(a)*(c));
secondMinusSolution /= 2*(a);
pValueStr = [firstPlusSolution stringValue];
mValueStr = [secondMinusSolution stringValue];
if ([NSString doesString:pValueStr containCharacter:'.']) { //category method I implemented
double fractionPart, integerPart;
fractionPart = modf(firstPlusSolution, &integerPart);
NSString *repeating = [NSString stringWithFormat:#"%g", fractionPart];
int repNum, tempNum;
BOOL repeat = NO;
//do for loop and check for negatives, integers, etc.
}
if ([NSString doesString:mValueStr containCharacter'.']) {
//do above code
//do for loop and check again
}
Use C. Take the fractional part. Convert to a string with a known accuracy. If length of string indicates that last digits are missing, then it does not repeat. Use NSString-UTF8String to convert a string. Get rid of the last digit (may be rounding or actual floating point arithmetic error). Use function int strncmp ( const char * str1, const char * str2, size_t num ) to perform comparison within the string itself. If the result is 8 characters long and the last 2 characters match the first 2 characters, then shall the first 6 characters be considered repeating?
Assuming that fraction knowledge your desire:
• Possibility 1: Use fractions. Input fractions. Compute with fractions. Output fractions. Expand upon one of the many examples of a c++ fraction class if necessary and use it.
• Possibility 2: Choose an accuracy which is much less than double. Make a fraction from the result. Reduce the fraction allowing rounding based upon accuracy.
I suggest use not optimal but easy to write solution
Create NSMutableDictionary that will contain number as key and count of occurrence as value.
You can use componentsSeparatedByString: if numbers in string delimited by known symbol
In loop check valueForKey in dictionary and if need increase value
Last step is analyzing our dictionary and do anything you need with numbers

Concatenating an int to a string in Objective-c

How do I concatenate the int length to the string I'm trying to slap into that array so it is "C10" given length == 10, of course. I see #"%d", intVarName way of doing it used else where. In Java I would of done "C" + length;. I am using the replaceObjectAtIndex method to replace the empty string, "", that I have previously populated the MSMutableArray "board" with. I am getting an error though when I add the #"C%d", length part at the end of that method (second to last line, above i++).
As part of my homework I have to randomly place "Chutes" (represented by a string of format, "C'length_of_chute'", in this first assignment they will always be of length 10 so it will simply be "C10") onto a game board represented by an array.
-(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
//??Make argument number of Chutes ??randomly?? across the board.
for(int i = 0; i < length;){
int random = arc4random_uniform(101);
if ([[board objectAtIndex:random] isEqual:#""]) {
//[board insertObject:#"C%d",length atIndex:random];
[board replaceObjectAtIndex:random withObject:#"C%d",length];
i++;
}
}
}
Please ignore the extra and junk code in there, I left it in for context.
In Objective-C the stringWithFormat method is used for formatting strings:
NSString *formattedString = [NSString stringWithFormat:#"C%d", length];
[someArray insertObject:formattedString];
It's often easier to create your formatted string on a line of its own in Objective-C, since as you can see the call can be fairly verbose!

Show Unicode characters in text field

I have a slider for testing and I want the characters represented by the slider position to be shown in a text field. But my text field only shows A-Z and a-z when running my solution below. How can I get Unicode characters into my text field?
- (IBAction) doSlider: (id) sender
{
long long theNum = [sender intValue];
NSString *vc_theString = [NSString stringWithFormat:#"%c", theNum];
[charField setStringValue:vc_theString2];
}
%c is inherited from C and limited to an 8-bit range. You should use %C, which will read in the corresponding argument as a unichar.