how to convert value one format into the another format? - iphone

This is my Button method. When I press the button it's value is every time increment one & display into Label. Then it's reach 6 then convert like 1.0 , 7 = 1.1, 8 = 1.2 , 12 like 2.0 like cricket over format.
How can I do that?
-(void)OneNoBTNPressedMethod
{
// LBL it's my label & display the text
NSString * overStorage = LBL.text;
// perform the addition operation
CalcOperation operation;
operation = Plus;
//add one every time when we press the button
NSString * overOneBTNStr = [NSString stringWithFormat:#"1"];
NSString *overVal = overOneBTNStr;
LBL.text= [NSString stringWithFormat:#"%qi",[overVal longLongValue]+[overStorage longLongValue]];
}
Thanx in advance..

It worked for me. Hope it works for you as well. Assuming your LBL contains "1" as initial text. hope it helps
- OneNoBTNPressedMethod {
NSString *str = LBL.text;
NSArray *arr = [str componentsSeparatedByString:#"."];
if ([arr count] == 1) {
if ([LBL.text intValue] >= 5) {
LBL.text = [NSString stringWithFormat:#"%i.%i",0,0];
} else {
LBL.text = [NSString stringWithFormat:#"%i",[LBL.text intValue] + 1];
}
} else if ([arr count] == 2) {
if ([[arr objectAtIndex:1] intValue] >= 5) {
int left = [[arr objectAtIndex:0] intValue] + 1;
LBL.text = [NSString stringWithFormat:#"%i.%i",left,0];
} else {
LBL.text = [NSString stringWithFormat:#"%i.%i",[[arr objectAtIndex:0] intValue],[[arr objectAtIndex:1] intValue] + 1];
}
}
}

Try this logic
Let `int num` is count
Then
numBeforeDecimal = num/6;
numAfterDecimal = num%6;
Concatenate both number
[NSString stringWithFormat: #"%d.%d",numBeforeDecimal,numAfterDecimal];

Related

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

how to get digits of a integer from NSString?

I am having a string like NSString *str = #"123".I want to fill the digits of this string into UIPickerView.But how to get the digits from this string?I added the following code
- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component
{
int number = [str intValue];
if(component == 0)
{
}
else if(component == 1)
{
}
else
{
}
}
Please see this..
NSMutableArray *arrNumbers = [[NSMutableArray] alloc] initWithCapacity:[YOURSTRING length]];
for (i=0;i<[YOURSTRING length];i++)
{
  unichaar ch = [YOURSTRING characterAtIndex:i];
  NSLog(#"Processing charachter %c",ch);
  // If you really want
  [arrNumbers addObject:(id)ch];
}
Other solutions seem to be excessive, considering NSString is already an array of characters. More lightweight solution:
NSString *str = #"123";
for (int i = 0; i < [str length]; i++) {
int digit = [str characterAtIndex:i] - '0';
// do something with your digit
}
If you have it as a string you can just do
NSArray * digitStrings = [str componentsSeparatedByString:""];
And each element in the array would be a digit as a NSString.
not tested but you can give it a try, this is supposed to scan all numeric entries of your string.
-(NSArray*)getDigitsFromString:(NSString*)str{
NSMutableString *outpuString = [NSMutableString
stringWithCapacity:str.length];
NSScanner *scanner = [NSScanner scannerWithString:str];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[outpuString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSArray * digitStr = [outpuString componentsSeparatedByString:#""];
return digitStr;
}
NSMutableArray * digit=[[NSMutableArray alloc]init];
NSString *string = #"123456";
for (int i=0;i<[string length]; i++) {
NSString * newString = [string substringWithRange:NSMakeRange(i, 1)];
[digit addObject:newString];
}
NSLog(#"String %# ", digit)
One more answer which addresses more the idea of the original question by solving the problem of separating an int into it's digits:
NSString *numberString = #"68243";
int result[numberString.length];
NSInteger number = [numberString integerValue];
int j = numberString.length - 1;
while (j >= 0)
{
int power = pow(10, j);
int rest = (number % power);
result[j] = (number - rest)/power;
number = rest;
j--;
}

How to assign the NSArray string object values to other NSString variables

NSMutableArray *nameArray = [[NSMutableArray alloc] init];
[nameArray addObject:#"abc"];
[nameArray addObject:#"cdf"];
[nameArray addObject:#"jkl"];
//Use a for each loop to iterate through the array
for (NSString *s in nameArray) {
NSLog(#"value is %#", s);
}
The above code shows all the values of nameArray. But I want to assign all those values to these NSString:
NSString *a;
NSString *b;
NSString *cd;
An aray can have 1 or more elements but not more than 5.
Actually,I have 5 buttons, each button on click will add a NSString value(values are: f1,f2,f3,f4 and f5) to NSMutableArray. Now its upto the user if he clicks 2 buttons or 3 or 5 in a day. Now all these values will be saved in NSMutableArray (which can be 1 or 2 but not more than 5). That NSMutableArray will be saved in NSUserDefaults. This NSMutableArray than will be used in another view where I have some UIImageView (1,2,3,4 and 5). Now when I will get the string values from that Array(f1,f2,f3). If it is f1 then an image will be assigned to UIImage 1 if it is f3 then to image 3 and so on.
How to achieve this?
I would do something like that:
NSArray *array = [NSArray arrayWithObjects:#"A", #"B", #"C", #"D", #"E", nil];
NSString *a = nil, *b = nil, *c = nil, *d = nil, *e = nil;
NSUInteger idx = 0;
for ( NSString *string in array )
{
switch ( idx++ ) {
case 0: a = string; break;
case 1: b = string; break;
case 2: c = string; break;
case 3: d = string; break;
case 4: e = string; break;
}
}
As at least one element will be there in your array:
NSString *a = (NSString *)[nameArray objectAtIndex:0];
As maximum will be five elements:
for(int i = 1;i<[array count];i++)
{
if(i == 1)
{
NSString *b = (NSString *)[nameArray objectAtIndex:1];
}
else if(i == 2)
{
NSString *c = (NSString *)[nameArray objectAtIndex:2];
}
else if(i == 3)
{
NSString *d = (NSString *)[nameArray objectAtIndex:3];
}
else if(i == 4)
{
NSString *e = (NSString *)[nameArray objectAtIndex:4];
}
}
a = [nameArray objectAtIndex:0];
b = [nameArray objectAtIndex:1];
cd = [nameArray objectAtIndex:2];
If you want to put your array elements into separate variables with distinct names, there is no automation in objective c (unlike say, in JavaScript) since it is a compiled and not a interpreted language. Something similar you can achieve with NSDictionary, i.e. to "index" objects with strings or whatever type you want.
You could go on with a simple C array of 5 unsigned chars, where the index of the array would point to your data. Something like this:
unsigned char nameArray[5] = {0, 0, 0, 0, 0};
// if you want to set the 3rd variable, use:
nameArray[2] = 1;
// to query:
if (nameArray[2]) { ... }
// When you need to save it to NSUserDefaults, wrap it into an NSData:
NSData* nameData = [NSData dataWithBytes:nameArray length:sizeof(nameArray)];
[[NSUserDefaults standardUserDefaults] setObject:nameData forKey:#"myKey"];
// To query it:
NSData* nameData = [[NSUserDefaults standardUserDefaults] dataForKey:#"myKey"];
const unsigned char* nameArray2 = [nameData bytes];
unsigned char second = nameArray2[2];
EDITED: corrected array access
If there is at most five options the easiest way to do it is with an if-else-if chain.
NSString *label1 = nil, *label2 = nil, *label3 = nil, *label4 = nil, *label5 = nil;
for (NSString *s in nameArray) {
if (label1 == nil)
label1 = s;
else if (label2 == nil)
label2 = s;
else if (label3 == nil)
label3 = s;
else if (label4 == nil)
label4 = s;
else if (label5 == nil)
label5 = s;
}
NSString *str1=nil;
NSString *str2=nil;
NSString *str3=nil;
NSString *str4=nil;
for (LocationObject *objLoc in arrLocListFirstView)
{
if (objLoc.isLocSelected)
{
for (LocationObject *obj in arrLocListFirstView)
{
if (str1 == nil)
str1 = objLoc.strLoc;
else if (str2 == nil)
str2 = obj.strLoc;
else if (str3 == nil)
str3 = obj.strLoc;
else if (str4 == nil)
str4 = obj.strLoc;
}
NSString *combined = [NSString stringWithFormat:#"%#,%#,%#,%#", str1,str2,str3,str4];
lblLocation.text=combined; (displaying text in UILabel)
}
}

How to use RegexKitLite correctly

I am using RegexKitLite, i want to validate that my uitextfield has + prefixed and contains numeric length of 13 or only 13 numeric values.
Please let me know
Below is the code i tried
textview.text = #"123458kdkmfmdfmsdf"
NSString *regEx = #"{3}-[0-9]{3}-[0-9]{4}";
NSString *match = [textView.text stringByMatching:regEx];
if ([match isEqual:#""] == NO)
{ NSLog(#"Phone number is %#", match); }
else { NSLog(#"Not found."); }
the ouput i want is belo
ouput 1 = "1234567891012"
or output 2 can be like "+1234567891012
try this :
NSString * forAlphaNumeric = #"^([+]{1})(a-zA-Z0-9{13})$";
BOOL isMatch = [yourString isMatchedByRegex:forAlphaNumeric];
NSString * forNumeric = #"^([+]{1})(0-9{13})$";
BOOL isMatch = [yourString isMatchedByRegex:forNumeric];

How to convert Hex to Binary iphone

I need to convert a hex string to binary form in objective-c, Could someone please guide me?
For example if i have a hex string 7fefff78, i want to convert it to 1111111111011111111111101111000?
BR,
Suppi
Nice recursive solution...
NSString *hex = #"49cf3e";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt]];
-(NSString *)toBinary:(NSUInteger)input
{
if (input == 1 || input == 0)
return [NSString stringWithFormat:#"%u", input];
return [NSString stringWithFormat:#"%#%u", [self toBinary:input / 2], input % 2];
}
Simply convert each digit one by one: 0 -> 0000, 7 -> 0111, F -> 1111, etc. A little lookup table could make this very concise.
The beauty of number bases that are powers of another base :-)
In case you need leading zeros, for example 18 returns 00011000 instead of 11000
-(NSString *)toBinary:(NSUInteger)input strLength:(int)length{
if (input == 1 || input == 0){
NSString *str=[NSString stringWithFormat:#"%u", input];
return str;
}
else {
NSString *str=[NSString stringWithFormat:#"%#%u", [self toBinary:input / 2 strLength:0], input % 2];
if(length>0){
int reqInt = length * 4;
for(int i= [str length];i < reqInt;i++){
str=[NSString stringWithFormat:#"%#%#",#"0",str];
}
}
return str;
}
}
NSString *hex = #"58";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt strLength:[hex length]]];
NSLog(#"binario %#",binary);
I agree with kerrek SB's answer and tried this.
Its work for me.
+(NSString *)convertBinaryToHex:(NSString *) strBinary
{
NSString *strResult = #"";
NSDictionary *dictBinToHax = [[NSDictionary alloc] initWithObjectsAndKeys:
#"0",#"0000",
#"1",#"0001",
#"2",#"0010",
#"3",#"0011",
#"4",#"0100",
#"5",#"0101",
#"6",#"0110",
#"7",#"0111",
#"8",#"1000",
#"9",#"1001",
#"A",#"1010",
#"B",#"1011",
#"C",#"1100",
#"D",#"1101",
#"E",#"1110",
#"F",#"1111", nil];
for (int i = 0;i < [strBinary length]; i+=4)
{
NSString *strBinaryKey = [strBinary substringWithRange: NSMakeRange(i, 4)];
strResult = [NSString stringWithFormat:#"%#%#",strResult,[dictBinToHax valueForKey:strBinaryKey]];
}
return strResult;
}