RAMAN RANA
RAMAN RANA

Reputation: 1795

Add character or special character in NString?

I have an NSString *string=@"606" and I want to add a ":" colon after two digits.
The output should look like this: 6:06
It this is possible?

Help would be appropriated.
Thank you very much.

Upvotes: 0

Views: 237

Answers (3)

Bill Burgess
Bill Burgess

Reputation: 14154

Will it be 2 digits no matter what? Otherwise you could build your custom string from parameters.

NSString *string = [NSString stringWithFormat:@"%@:%@", hours, minutes];

UPDATE

If you just need to add a colon after 1 char, you can do it this way. Although I would suggest finding a safer method as this could be inaccurate if you have a double digit hour.

NSString *hour = [NSString substringToIndex:1]; // double check the index
NSString *min = [NSString substringFromIndex:1]; // double check the index
NSString *time = [NSString stringWithFormat:@"%@:%@", hour, min];

Hopefully this will help.

Upvotes: 0

Evan Mulawski
Evan Mulawski

Reputation: 55334

Because you do not have two separate objects for hours and minutes, use:

NSString *newTimeString, *hour, *minute;
NSUInteger length = [timeString length];
if (length == 3)
{
    hour = [timeString substringToIndex:1];
    minute = [timeString substringFromIndex:2];
}
else
{
    hour = [timeString substringToIndex:2];
    minute = [timeString substringFromIndex:3];
}
newTimeString = [NSString stringWithFormat:@"%@:%@", hour, minute];

I used a long version to illustrate the concept. Basically, use the length of the original string (timeString) to extract the time components and combine them with a colon.

Upvotes: 2

sch
sch

Reputation: 27506

You can add the column between the hours and the minutes like this:

NSString *string = @"606";
NSString *result = [string stringByReplacingCharactersInRange:NSMakeRange(string.length-2, 0) withString:@":"];
NSLog(@"%@", result);

This will give the following results

@"606"  =>  @"6:06"
@"1200" =>  @"12:00"
@"1406" =>  @"14:30"

Note: This will only work if the string has 3 or 4 characters, but this is the case according to your question.

Upvotes: 3

Related Questions