All,
I can't seem to find the answer I'm looking for using search so I'll ask it.
I need to pull the last four digits of a credit card number out and set it into another string. It needs to account for the variances in credit card number lengths (i.e. 16 numbers or 15 numbers, etc)
i.e. if the number was "1234567890123456" I would want to set a new string as "3456".
Thanks
Assuming the credit card number is stored as a string:
NSString *lastFour = [fullNumber substringFromIndex:[fullNumber length] - 4];
Assuming it's an unsigned integer of any wide-enough type:
NSString *lastFour = [NSString stringWithFormat: #"%04u", (unsigned int)(fullNumber % 10000)];
NSString *newString = [oldString substringFromIndex:[oldString length] - 4];
Related
I have to convert an NSNumber to a hex string like follows:
return [NSString stringWithFormat:#"%llX", self.unsignedLongLongValue];
Unfortunately, this will sometimes give me string like 93728A166D1A287 where they should be 093728A166D1A287, depending on the number.
Hint: the leading 0.
I've also tried it with:
return [NSString stringWithFormat:#"%16.llX", self.unsignedLongLongValue];
without success.
I could do something like this, but that just sucks:
- (NSString *)hexValue {
NSString *hex = [NSString stringWithFormat:#"%llX", self.unsignedLongLongValue];
NSUInteger digitsLeft = 16 - hex.length;
if (digitsLeft > 0) {
NSMutableString *zeros = [[NSMutableString alloc] init];
for (int i = 0; i < digitsLeft; i++) [zeros appendString:#"0"];
hex = [zeros stringByAppendingString:hex];
}
return hex;
}
So finally my question, is there a way to enforce the string to be 16 characters?
If you need to zero-pad your hex numbers, use zero in front of the format specifier, like this:
return [NSString stringWithFormat:#"%016llX", self.unsignedLongLongValue];
This should take care of formatting your number with 16 digits, regardless of how many "meaningful" digits the number has.
Here is a demo of this format string in plain C (this part is shared between the two languages).
Use:
return [NSString stringWithFormat:#"%016llX", self.unsignedLongLongValue];
Which sets leading 0 and the length of the output string.
I am receiving a string from server in this format:
0_1_2_3
My task is to select for digits from this string to fill four labels with them.
First idea was:
NSString *res1 = [result substringWithRange:NSMakeRange(0, 1)];
[firstLabel setText:res1];
four times with appropriate labels.
But operation will repeats many times and every time I will receive a string with increased digit values. So when every digit be a decimal this code will not work. So how can I track every digit independently from their length in a proper way?
NSString comes with a convenience method called -componentsSeparatedByString:
NSString *myString = #"0_1_2_3";
NSArray *myDigitStrings = [myString componentsSeparatedByString:#"_"];
/* access digit strings from myDigitStrings array by index or fast enumeration... */
for (NSString *myDigitString in myDigitStrings)
NSLog(#"digit string: %#", myDigitString);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
It might be the simplest Question, but at this time ,I am not getting any Idea on how to implement this.
Ok, The problem is of how to concatenate two integers.
For Eg: I want to create an integer say 0000 using two different integers 00 and 00. I tried using NSString , but I failed.
My Code is :
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %d",num); // It Logs 0 but I want 0000.
Does anyone have better Idea ?
EDIT :
Please Note that , I want to use that num to set the tag of textfield. That's why all the zeros are essential. So my main Problem starts here.
I have one tableview which contains custom cells. This custom cell has more than 10 textfields. Now I want to uniquely identify all the textfields for editing. That's why the tag for that textfield must be the integer concatenated by two values called rowNumber and textFieldNumber (means which textField out of 10.).
So my question is what I am trying to do is right or not ? And if not then give me some useful solution.
The integer data types (such as int) only store the integer value, not formatting information. Therefore you lose the number of leading zeroes (which do not affect the integer value, i.e., 0, 00, and 0000 are the same integer: zero).
If you wish to retain formatting information, you must store it separately. A simple way is to just store the string itself. Or, if you always want to have the same number of digits, then alter the formatting string:
int num1 = 0;
int num2 = 0;
NSString *str = [NSString stringWithFormat:#"%02d%02d",num1,num2];
After the above code, str will be "0000". However, converting it to int and then logging with %d formatting results in 0 once more (since 0000 and 0 are the same integer).
Edit: For the purpose of generating unique integers for tagging purposes, given a row number (rowNumber) and text field number (textFieldNumber), use a formula like:
tagNumber = rowNumber * 100 + textFieldNumber;
This way the text fields of row 0 will have numbers 0..99, those on row 1 will have 100..199, etc. If more than 100 text fields are required per row, simply multiply by a larger number, like 1000.
In integer arithmetic these values can be converted back to row and field numbers with:
rowNumber = tagNumber / 100;
textFieldNumber = tagNumber % 100;
Try to use this:
int num1 = 0;
int num2 = 0;
int num3=0;
int num4=0;
NSString *str = [NSString stringWithFormat:#"%d%d%d%d",num1,num2,num2,num3];
int num = [str intValue];
NSLog(#"num = %0*d",str.length,num);
Hope this helps you.
but dont init as like this "int num1=00" because it init "0" only in num1.
Why turn it back into an int? You should print the string you just formatted:
NSLog(#"num = %#",str);
As numbers, there is no difference between 0 and 0000. Integers only preserve the value, not the formatting (that's what strings are for).
Multiply the first integer with 100 and add the second integer to it. You should be able to print it using:
NSLog([NSString stringWithFormat:#"%04d", sum]);
which will put leading zeros.
You can pad it as :
NOTE: both the num1 and num2 must be of 2 digits. If its size increases then it wont work.
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %04d",num);
If printing is not the real issue then i guess you need a multiplication factor to set the tag
let it be 10000 and add it to some sequence no to get the unique tag value.
or you can use num as string and multiply by 10 in for loop for num.length times
I am trying to convert an int to a string in objective-C.
I read the other questions on SO about converting ints to strings, and I tried this method in my code:
-(void)setCounter:(int)count
{
counterText.text = [NSString stringWithFormat:#"%d",count];
}
However, if I want to display a number like '01' the 0 is taken out of the conversion and only '1' is displayed. Is there a workaround?
There is no such number as 01. If you write
int count = 01;
it is compiled equivalently to
int count = 1;
In fact, be careful: 07 is equivalent to 7, but 011 is equivalent to 9!
What you can do is ask stringWithFormat: to give you the zero-padding:
[NSString stringWithFormat:#"%02d",count]
should give you "02" if count is 2. To deconstruct it:
% - interpolate the next value here
0 - pad it to the width by placing zeroes on the left side
2 - width is 2 characters
d - it will be an integer. Do it now.
If you want a different format to the one shown, use it:
counterText.text = [NSString stringWithFormat:#"%02d",count];
There are a huge range of possibilities with the format string.
if any number start from 0 then Its a octal representation (0 - 7). you can add zero explictly using below line.
counterText.text = [NSString stringWithFormat:#"0%d",count];
Check out..
NSNumber +numberWithInt
and then:
NSNumberFormatter -setMinimumIntegerDigits
and then get the string representation with:
NSString -stringFromNumber
Can someone give a code example of how to right pad an NSString in objective-c please?
For example want these strings:
Testing 123 Long String
Hello World
Short
if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:
Testing 123 xxx
Hello World xxx
Short xxx
That is a 2nd column would like up.
Adam is on the right track, but not quite there. You do want to use +stringWithFormat:, but not quite as he suggested. If you want to pad "someString" to (say) a minimum of 12 characters, you'd use a width specifier as part of the format. Since you want the result to be left-justified, you need to precede the width specifier with a minus:
NSString *padded = [NSString stringWithFormat:#"%-12#", someString];
Or, if you wanted the result to be exactly 12 characters, you can use both minimum and maximum width specifiers:
NSString *padded = [NSString stringWithFormat:#"%-12.12#", someString];
2nd column of what would line up?
Given that you are on iOS, using HTML or a table view would be far more straightforward than trying to line up characters with spaces. Beyond being programmatically more elegant, it will look better, be more resilient to input data changes over time, and render a user experience more in line with expectations for the platform.
If you really want to use spaces, then you are going to have to limit your UI to a monospace font (ugly for readability purposes outside of specific contexts, like source code) and international characters are going to be a bit of a pain.
From there, it would be a matter of getting the string length (keeping in mind that "length" does not necessarily mean "# of characters" in some languages), doing a bit of math, using substringWithRange: and appending spaces to the result.
Unfortunately, Objective-C does not allow format specifiers for %#. A work-around for padding is the following:
NSString *padded = [NSString stringWithFormat:#"%#%*s", someString, 12-someString.length, ""];
which will pad the string to the right with spaces up to a field length of 12 characters.
%-# does not work, but %-s works
NSString *x = [NSString stringWithFormat:#"%-3#", #"a" ];
NSString *y = [NSString stringWithFormat:#"%-3#", #"abcd" ];
NSString *z = [NSString stringWithFormat:#"%-3# %#", #"a", #"bc" ];
NSString *zz = [NSString stringWithFormat:#"%-3s %#", "a", #"bc" ];
NSLog(#"[%#][%#][%#][%#].......", x,y,z,zz);
output:
[a][abcd][a bc][a bc].......
Try below. its working for me.
NSString *someString = #"1234";
NSString *padded = [someString stringByPaddingToLength: 16 withString: #"x" startingAtIndex:0];
NSLog(#"%#", someString);
NSLog(#"%#", padded);
First up, you're doing this a bad way. Please use separate labels for your two columns and then you will also be able to use proportional fonts. The way you're going about it you should be looking for an iPhone curses library.
If you really have to do it this way just use stringWithFormat:, like:
NSString *secondColumnString = #"xxx";
NSString *spacedOutString = [NSString stringWithFormat:#"testingColOne %#", secondColumnString];
NSString *spacedOutString = [NSString stringWithFormat:#"testingAgain %#", secondColumnString];