Add character or special character in NString? - iphone

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.

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.

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.

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.

Related

Replace a character in a String iPhone

I want to replace a single character at a particular position in a string.
Example
String: 123-456-7890
Desired Output: 123-406-7890 (Replacing 5 at fifth position with 0)
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
visit here and read all about string
Use stringByReplacingCharactersInRange:withString:, forming the NSRange variable to indicate the 5th position.
NSString *phoneNumber = #"123-456-7890";
NSString *newString = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(5, 1) withString:#"0"];
NSLog(#"%#", newString);
Output: 123-406-7890
Read all about NSString.
for replacing string there are lots of way:
NSString *str = [yourString stringByReplacingOccuranceOfString:#"5" withString:#"0"];
second way first get range of string like:
NSRange range = [yourSting rangeOfString:#"5"];
NSString *first = [yourString substringToIndex:range.location];
NSString *second = [yourString substringFromIndex:range.location+range.length];
NSString *yourNewStr = [NSString stringWithFormat:#"%#0%#",first,second];
Tere are lots of other using string operation but First one is best in that.
Get the range (i.e. index) of first occurrence of the substring.
Then replace at that range with your desired replace value.
NSString *originalString = #"123 456 789";
NSRange r = [originalString rangeOfString:#"5"];
NSString *newString = [originalString stringByReplacingCharactersInRange:r withString:#"0"];
If you want to actually replace the 5th character rather than just any 5 you need to make a range first.
NSRange range = NSMakeRange(5, 1);
NSString *newString = [initialString stringByReplacingCharactersInRange:range withString:#"0"];
Edit: Corrected make range length
you can use :-
NSString *replacechar = #"0";
NSString *newString= [String stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:replacechar];

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

Unexpected result from "stringWithFormat:"

What would be the expected result from the following Objective C code?
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%+02d", intValue];
I thought the value of string would be "+01", it turns out to be "+1". Somehow "0" in format string "+01" is ignored. Change code to:
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string is now "01". It does generate the leading "0". However, if intValue is negative, as in:
int intValue = -1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string becomes "-1", not "-01".
Did I miss anything? Or is this a known issue? What would be the recommended workaround?
Thanks in advance.
#Mark Byers is correct in his comment. Specifying '0' pads the significant digits with '0' with respect to the sign '+/-'. Instead of '0' use dot '.' which pads the significant digits with '0' irrespective of the sign.
[... stringWithFormat:#"%+.2d", 1]; // Result is #"+01"
[... stringWithFormat:#"%.2d", -1]; // Result is #"-01"
NSString *string = [NSString stringWithFormat:#"+0%d", intValue];
NSString *string = [NSString stringWithFormat:#"-0%d", intValue];

String to double

I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.
NSString *stringValue = #"1235";
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/(double)100.00];
I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.
I have tried:
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue intValue]/(double)100.00];
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/100];
but all without success.
This is how to convert an NSString to a double
double myDouble = [myString doubleValue];
You have to use %f to show float/double value.
then %.2f means 2digits after dot
NSString *stringValue = #"1235";
NSString *str = [NSString stringWithFormat:#"%.2f",[stringValue doubleValue]/(double)100.00];
NSLog(#"str : %# \n\n",s);
priceLabel.text = str;
OUTPUT:
str : 12.35
I think you have the wrong format string. Where you have:
[NSString stringWithFormat:#"%d", ...];
You should really have:
[NSString stringWithFormat:#"%f", ...];
%d is used for integer values. But you're trying to display a floating point number (%f).