Right, basically I want to add two numbers together. It's for a working hours calculator and I've included parameters for a night shift scenario as an if statement. However, it now mucks up the day shift pattern. So I want to sort out that if the start time is below 12, then it'll revert to the original equation shown in the code instead of the if statement.
-(IBAction)done:(id)sender {
int result = [finishHours.text intValue] - [startHours.text intValue];
totalHours.text = [NSString stringWithFormat:#"%d", result];
if (result < 0) {
totalHours.text = [NSString stringWithFormat:#"%d", result * -1];
}
if (result < 12) {
totalHours.text = [NSString stringWithFormat:#"%d", result + 24];
}
if (startHours < 12) {
totalHours.text = [NSString stringWithFormat:#"%d", result - 24];
}
Both of those if statements are going to happen for result. I would suggest an if statement that includes greater than zero and less than 12.
if((result >= 0) && (result < 12))
{
totalHours.text = [NSString stringWithFormat:#"%d", result + 24];
}
Related
I am trying to take a string (#"12345") and extractor each individual character and convert to it's decimal equivalent.
#"1" = 1
#"2" = 2
etc.
Here is what I have this far:
...
[self ArrayOrder:#"1234"];
...
-(void)ArrayOrder(Nsstring *)Directions
{
NSString *singleDirections = [[NSString alloc] init];
//Loop Starts Here
*singleDirection = [[Directions characterAtIndex:x] intValue];
//Loop ends here
}
I have been receiving type errors.
The problem with your code is that [Directions characterAtIndex:x] returns a unichar, which is a Unicode character.
Instead, you can use NSRange and substrings to get each number out of the string:
NSRange range;
range.length = 1;
for(int i = 0; i < Directions.length; i++) {
range.location = i;
NSString *s = [Directions substringWithRange:range];
int value = [s integerValue];
NSLog(#"value = %d", value);
}
Another approach would be to use / 10 and % 10 to get to each number from the string individually. Such as:
NSString* Directions = #"1234";
int value = [Directions intValue];
int single = 0;
while(value > 0) {
single = value % 10;
NSLog(#"value is %d", single);
value /= 10;
}
However, that goes through your string backwards.
I am new to Objective-C and would like some help with converting MPS to KPH.
Below is my current string for speed. Can someone please point out what else is needed?
speed.text = newLocation.speed < 0 ? #"N/A": [NSString stringWithFormat:#"%d", (int)newLocation.speed];
m/s to km/h = (m/s) * (60*60)/1000
Or 1m/s = 3.6km/h
float speedInKilometersPerHour = newLocation.speed*3.6;
if (speedInKilometersPerHour!=0) {speed.text = [NSString stringWithFormat:#"%f", speedInKilometersPerHour];}
else speed.text = [NSString stringWithFormat:#"No Data Available"];
Assuming you mean Meters Per Second to Kilometers Per Hour, and you want us to modify your existing ternary, than this would do the job.
speed.text = (newLocation.speed < 0) ? (#"N/A") : ([NSString stringWithFormat:#"%d", (int)(newLocation.speed*3.6)]);
If the original speed in MPS was less than zero, than its not applicable, otherwise it converts it.
You should also probably round the result to the nearest integer, so that it's more accurate.
speed.text = (newLocation.speed < 0) ? (#"N/A") : ([NSString stringWithFormat:#"%d", (int)((newLocation.speed*3.6)+0.5)]);
Here is one way to do it (I've formatted it to be a little more readable):
if (newLocation.speed < 0)
speed.text = #"N/A";
else
speed.text = [NSString stringWithFormat:#"%d", (int)(newLocation.speed * 3.6)];
Note however, that you really should be using a number formatter to convert the number to a localized string before displaying it to the user so that it is formatted correctly in their own locale:
if (newLocation.speed < 0)
{
speed.text = #"N/A";
}
else
{
int speedKPH = (int)(newLocation.speed * 3.6);
NSNumber *number = [NSNumber numberWithInt:speedKPH];
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
speed.text = [formatter stringFromNumber:number];
}
I want to remove the preceding zeros from phone number's country code.
I take it as NSString because phone number contains symbols such as + , ( , ) , - .
I need those symbols.
e.g
Input:-
1) NSString *phNo = #"0011234567890";
2) NSString *phNo2 = #"0601234567999";
Output:-
1) 11234567890
2) 601234567999
What I did is as follows
if ([phNo length]>10) {
NSString *countryCodeSubString = [phNo substringToIndex:[phNo length]-10];
if ([[countryCodeSubString substringToIndex:1]isEqualToString:#"0"]) {
for (int i=0; i<[countryCodeSubString length]; i++) {
NSString *str = [countryCodeSubString substringToIndex:i];
if ([str isEqualToString:#"0"]) {
str = [str stringByReplacingOccurrencesOfString:#"0" withString:#""];
}
}
}
}
I know above code is wrong.
Can anybody help me with this ? How can I do this efficiently ?
int firstNonZeroCharIndex = -1;
for (int i=0; i<phNo.length; ++i) {
if ([phNo.characterAtIndex:i] != '0') {
firstNonZeroCharIndex = i;
break;
}
}
if (firstNonZeroCharIndex != -1) {
phNo = [phNo subStringFromIndex:firstNonZeroCharIndex];
}
If you just want to get the preceding zeroes off, then you can do simply like this.
NSString *phNo = #"0011234567890";
float number = [phNo floatValue];
NSString *phNoWithOutZero = [NSString stringWithFormat:#"%1.0f", number];
But this will not work it the string have any special characters except number.
I’m trying to make a counter which shows the number of days until we leave on a trip to Europe. It’s only about 70 days (as of today) so I don’t believe that I should have to worry about astronomically large numbers or anything, but I really am stumped - I’ve attached the code that some friends have given me, which don’t work either. Trust me when I say I’ve tried everything I can think of - and before anyone bites my head off, which I have seen done on these forums, yes I did look very extensively at the Apple Documentation, however I’m not 100% sure where to start - I’ve tried NSTimer, NSDate and all their subclasses and methods, but there’s nothing that jumps out immediately.
In terms of what I think I should actually be doing, I think I need to somehow assign an integer value for the “day” today/ now/ the current day, which will change dynamically using the [NSDate date] and then the same for the date that we leave. The countdown is just updating when the method gets called again (I can do this using NSTimer if need be) and the value that is displayed on the countdown is the differnce between these two values.
I don’t especially want to have a flashing kind of thing that updates every second until we leave - personally I think that’s tacky, but if anyone knows how then I’d appreciate it for future reference.
I’ve also done an extensive search of google, and I may simply be using the wrong search terms, but I can’t find anything there either.
Any help is greatly appreciated.
Thank you very much.
Michaeljvdw
- (void)countDownMethod {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:startDay];
[comps setMonth:startMonth];
[comps setYear:startYear];
[comps setHour:startHour];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSLog(#"%#",date);
[gregorian release];
[comps release];
NSTimeInterval diff = [date timeIntervalSinceNow];
int diffInt = diff;
NSString *days = [NSString stringWithFormat:#"%d",diffInt/86400];
day0.text = #"0";
day1.text = #"0";
day2.text = #"0";
NSLog(#"Days Length: %d",days.length);
if(days.length >= 1){
day2.text = [days substringFromIndex:days.length - 1];
if(days.length >= 2){
day1.text = [days substringWithRange:NSMakeRange(days.length - 2, 1)];
if(days.length >= 3){
day0.text = [days substringWithRange:NSMakeRange(days.length - 3, 1)];
}
}
}
NSString *hours = [NSString stringWithFormat:#"%d",(diffInt%86400)/3600];
hour0.text = #"0";
hour1.text = #"0";
NSLog(#"Hours Length: %d",hours.length);
if(hours.length >= 1){
hour1.text = [hours substringFromIndex:hours.length - 1];
if(hours.length >= 2){
hour0.text = [hours substringWithRange:NSMakeRange(hours.length - 2, 1)];
}
}
NSString *minutes = [NSString stringWithFormat:#"%d",((diffInt%86400)%3600)/60];
minute0.text = #"0";
minute1.text = #"0";
NSLog(#"Minutes Length: %d",minutes.length);
if(minutes.length >= 1){
minute1.text = [minutes substringFromIndex:minutes.length - 1];
if(minutes.length >= 2){
minute0.text = [minutes substringWithRange:NSMakeRange(minutes.length - 2, 1)];
}
}
}
If you know the time in seconds between 2 dates (your NSTimeInterval) then you can easily convert that into a string in the format days:hours:mins:secs as follows.
- (NSString*)secsToDaysHoursMinutesSecondsString:(NSTimeInterval)theSeconds {
div_t r1 = div(theSeconds, 60*60*24);
NSInteger theDays = r1.quot;
NSInteger secsLeftFromDays = r1.rem;
div_t r2 = div(secsLeftFromDays, 60*60);
NSInteger theHours = r2.quot;
NSInteger secsLeftFromHours = r2.rem;
div_t r3 = div(secsLeftFromHours, 60);
NSInteger theMins = r3.quot;
NSInteger theSecs = r3.rem;
NSString* days;
if (theDays < 10) { // make it 2 digits
days = [NSString stringWithFormat:#"0%i", theDays];
} else {
days = [NSString stringWithFormat:#"%i", theDays];
}
NSString* hours;
if (theHours < 10) { // make it 2 digits
hours = [NSString stringWithFormat:#"0%i", theHours];
} else {
hours = [NSString stringWithFormat:#"%i", theHours];
}
NSString* mins;
if (theMins < 10) { // make it 2 digits
mins = [NSString stringWithFormat:#"0%i", theMins];
} else {
mins = [NSString stringWithFormat:#"%i", theMins];
}
NSString* secs;
if (theSecs < 10) { // make it 2 digits
secs = [NSString stringWithFormat:#"0%i", theSecs];
} else {
secs = [NSString stringWithFormat:#"%i", theSecs];
}
return [NSString stringWithFormat:#"%#:%#:%#:%#", days, hours, mins,secs];
}
//Another simple way to get the numbers of days difference to a future day from today.
NSTimeInterval todaysDiff = [todayDate timeIntervalSinceNow];
NSTimeInterval futureDiff = [futureDate timeIntervalSinceNow];
NSTimeInterval dateDiff = futureDiff - todaysDiff;
div_t r1 = div(dateDiff, 60*60*24);
NSInteger theDays = r1.quot;
label.text = [NSString stringWithFormat:#"%i", theDays];
Greetings,
I am new to objective c, and I have the following issue:
I have a NSString:
"There are seven words in this phrase"
I want to divide this into 3 smaller strings (and each smaller string can be no longer than 12 characters in length) but must contain whole words separated by a space, so that I end up with:
String1 = "There are" //(length is 9 including space)
String2 = "seven words"// (length is 11)
String3 = "in this" //(length is 7), with the word "phrase" ignored as this would exceed the maximum length of 12..
Currently I am splitting my original array into an array with:
NSArray *piecesOfOriginalString = [originalString componentsSeparatedByString:#" "];
Then I have multiple "if" statements to sort out situations where there are 3 words, but I want to make this more extensible for any array up to 39 (13 characters * 3 line) letters, with any characters >40 being ignored. Is there an easy way to divide a string based on words or "phrases" up to a certain length (in this case, 12)?
Something similar to this? (Dry-code warning)
NSArray *piecesOfOriginalString = [originalString componentsSeparatedByString:#" "];
NSMutableArray *phrases = [NSMutableArray array];
NSString *chunk = nil;
NSString *lastchunk = nil;
int i, count = [piecesOfOriginalString count];
for (i = 0; i < count; i++) {
lastchunk = [[chunk copy] autorelease];
if (chunk) {
chunk = [chunk stringByAppendingString:[NSString stringWithFormat:#" %#", [piecesOfOriginalString objectAtIndex:i]]];
} else {
chunk = [[[piecesOfOriginalString objectAtIndex:i] copy] autorelease];
}
if ([chunk length] > 12) {
[phrases addObject:lastchunk];
chunk = nil;
}
if ([phrases count] == 3) {
break;
}
}
well, you can keep splitting the string as you're already doing, or you could check out whether NSScanner suits your needs. In any case, you're going to have to do the math yourself.
Thanks McLemore, that is really helpful! I will try this immediately. My current solution is very similar, but less refined, as I hard coded the loops and use individual variable to hold the sub strings (called them TopRow, MidRow, and BottomRow), that and the memory management issue is overlooked... :
int maxLength = 12; // max chars per line (in each string)
int j=0; // for looping, j is the counter for managing the words in the "for" loop
TopRow = nil; //1st string
MidRow = nil; //2nd string
//BottomRow = nil; //third row string (not implemented yet)
BOOL Row01done = NO; // if YES, then stop trying to fill row 1
BOOL Row02done = NO; // if YES, then stop trying to fill row 2
largeArray = #"Larger string with multiple words";
tempArray = [largeArray componentsSeparatedByString:#" "];
for (j=0; j<[tempArray count]; j=j+1) {
if (TopRow == nil) {
TopRow = [tempArray objectAtIndex:j];
}
else {
if (Row01done == YES) {
if (MidRow == nil) {
MidRow = [tempArray objectAtIndex:j];
}
else {
if (Row02done == YES) {
//row 3 stuff goes here... unless I can rewrite as iterative loop...
//will need to uncommend BottomRow = nil; above..
}
else {
if ([MidRow length] + [[tempArray objectAtIndex:j] length] < maxLength) {
MidRow = [MidRow stringByAppendingString:#" "];
MidRow = [MidRow stringByAppendingString:[tempArray objectAtIndex:j]];
}
else {
Row02done = YES;
//j=j-1; // uncomment once BottowRow loop is implemented
}
}
}
}
else {
if (([TopRow length] + [[tempArray objectAtIndex:j] length]) < maxLength) {
TopRow = [TopRow stringByAppendingString:#" "];
TopRow = [TopRow stringByAppendingString:[tempArray objectAtIndex:j]];
}
else {
Row01done = YES;
j=j-1; //end of loop without adding the string to TopRow, subtract 1 from j and start over inside Mid Row
}
}
}
}