Addition with leading zeros in number - ios

I am receiving data in the form of a string from a database like so:
NSString *strTemp = #"000014";
I need to add 1 to the above,
like 000014 + 1 = 000015
000015 + 1 = 000016
depending on some count.
like:
for(int i =1; i < 5; i++)
{
int iTemp = [strTemp intValue] +i; // here i am getting 15 as int no not like 000015, 000016, 000017 ETC
}
I even tried NSString *strWarNo = [NSString stringWithFormat:#"%07d", iTemp]; but leading numbers may not be constant ...like string from db will be anything #"0023" or #"0000056".
I need to add one to while number, not only integer number.
How I can achieve this?

You can have a category over NSString to achieve this. I tried following code and its working fine.
.h of the category
#import <Foundation/Foundation.h>
#interface NSString (Arithematic)
- (NSString*)stringByAddingNumber:(NSInteger)number;
#end
.m of the category
#import "NSString+Arithematic.h"
#implementation NSString (Arithematic)
- (NSString*)stringByAddingNumber:(NSInteger)number
{
//To keep the width same as original string
int numberLength = (int)self.length;
NSInteger originalNumber = self.integerValue;
originalNumber += number;
NSString *resultString = [NSString stringWithFormat:#"%0*ld",numberLength,originalNumber];
return resultString;
}
#end
Usage:
NSString *strTemp = #"000014";
for(int i =1; i < 5; i++)
{
strTemp = [strTemp stringByAddingNumber:i];
}
NSLog(#"result %#",strTemp);
Hope this helps.

There is a simple way of doing this by converting string into NSInteger and then add your desired value into it and then convert the integer into string by appending you desired amount of zeros before then number.
-(NSString *)addNumber:(NSInteger)number toMyString:(NSString)myNum{
NSInteger numb = myString.integerValue;
numb += myNum;
NSString myNewString = [NSString stringWithFormat:#"0%d",myNewString];
return myNum;
}

If you want to format numbers with leading zeros then use NSNumberFormatter.
Store the number as a number (not a String) and then treat it like a number.
When you need to display it use an NSNumberFormatter to add leading zeros.
You can read more about NSNumberFormatter and adding leading zeros here... NSNumberFormatter leading 0's and decimals

Add which number you have to add in "num" and pass your number string "strNumber"
EX . [self addNumber:10 andYourString:#"000014"];
-(void)addNumber:(int)num andYourString:(NSString *)strNumber {
NSString * str_your_number = strNumber;
NSString * prevous_char = [NSString stringWithFormat:#"%c",
[str_your_number characterAtIndex:0]];
int number_zero = 0;
BOOL is_leading_zero = true;
for(int i = 0 ; i < str_your_number.length ; i++){
NSString *theCharacter = [NSString stringWithFormat:#"%c", [str_your_number characterAtIndex:i]];
if(is_leading_zero == true){
if([prevous_char isEqualToString:theCharacter]) {
number_zero++;
prevous_char = theCharacter;
}
else {
is_leading_zero = false;
}
}
NSLog(#"%#",theCharacter);
}
NSLog(#"%d",number_zero);
NSInteger you_numb = strNumber.integerValue;
you_numb += num;
NSString * str_zero = #"";
for(int j = 0 ; j < number_zero ; j++) {
str_zero = [str_zero stringByAppendingString:#"0"];
}
NSString * final_str = [NSString stringWithFormat:#"%#%ld",str_zero,(long)you_numb];
NSLog(#"%#",final_str);
}
it work...

Related

How to convert this value into absolute value?

I am getting this from webservice
"rateavg": "2.6111"
now i am getting this in a string.
How to do this that if it is coming 2.6 it will show 3 and if it will come 2.4 or 2.5 it will show 2 ?
How to get this i am not getting. please help me
Try This
float f=2.6;
NSLog(#"%.f",f);
Hope this helps.
I come up with this, a replica of your query:
NSString* str = #"2.611";
double duble = [str floatValue];
NSInteger final = 0;
if (duble > 2.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
So it a case of using either ceil or floor methods.
Edit: Since you want it for all doubles:
NSString* str = #"4.6";
double duble = [str floatValue];
NSInteger final = 0;
NSInteger temp = floor(duble);
double remainder = duble - temp;
if (remainder > 0.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
check this
float floatVal = 2.6111;
long roundedVal = lroundf(floatVal);
NSLog(#"%ld",roundedVal);
plz use this
lblHours.text =[NSString stringWithFormat:#"%.02f", [yourstrvalue doubleValue]];
update
NSString *a =#"2.67899";
NSString *b =[NSString stringWithFormat:#"%.01f", [a doubleValue]];
// b will contane only one vlue after decimal
NSArray *array = [b componentsSeparatedByString:#"."];
int yourRating;
if ([[array lastObject] integerValue] > 5) {
yourRating = [[array firstObject] intValue]+1;
}
else
{
yourRating = [[array firstObject] intValue];
}
NSLog(#"%d",yourRating);
Try below code I have tested it and work for every digits,
NSString *str = #"2.7";
NSArray *arr = [str componentsSeparatedByString:#"."];
NSString *firstDigit = [arr objectAtIndex:0];
NSString *secondDigit = [arr objectAtIndex:1];
if (secondDigit.length > 1) {
secondDigit = [secondDigit substringFromIndex:1];
}
int secondDigitIntValue = [secondDigit intValue];
int firstDigitIntValue = [firstDigit intValue];
if (secondDigitIntValue > 5) {
firstDigitIntValue = firstDigitIntValue + 1;
}
NSLog(#"final result : %d",firstDigitIntValue);
Or another solution - little bit short
NSString *str1 = #"2.444";
float my = [str1 floatValue];
NSString *resultString = [NSString stringWithFormat:#"%.f",my]; // if want result in string
NSLog(#"%#",resultString);
int resultInInt = [resultString intValue]; //if want result in integer
To round value to the nearest integer use roundf() function of math.
import math.h first:
#import "math.h"
Example,
float ValueToRoundPositive;
ValueToRoundPositive = 8.4;
int RoundedValue = (int)roundf(ValueToRoundPositive); //Output: 8
NSLog(#"roundf(%f) = %d", ValueToRoundPositive, RoundedValue);
float ValueToRoundNegative;
ValueToRoundNegative = -6.49;
int RoundedValueNegative = (int)roundf(ValueToRoundNegative); //Output: -6
NSLog(#"roundf(%f) = %d", ValueToRoundNegative, RoundedValueNegative);
Read doc here for more information:
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/roundf.3.html
NSString *value = #"1.23456";
float floatvalue = value.floatValue;
int rounded = roundf(floatvalue);
NSLog(#"%d",rounded);
if you what the round with greater value please use ceil(floatvalue)
if you what the round with lesser value please use floor(floatvalue)
You can round off decimal values by using NSNumberFormatter
There are some examples you can go through:
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setPositiveFormat:#"0.##"];
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.0]]);
Corresponding results:
2010-08-22 15:04:10.614 a.out[6954:903] 25.34
2010-08-22 15:04:10.616 a.out[6954:903] 25.3
2010-08-22 15:04:10.617 a.out[6954:903] 25
NSString* str = #"2.61111111";
double value = [str doubleValue];
2.5 -> 3: int num = value+0.5;
2.6 -> 3: int num = value+0.4;
Set as your need:
double factor = 0.4
if (value < 0) value *= -1;
int num = value+factor;
NSLog(#"%d",num);

How to convert a NSString to NSInteger with the sum of ASCII values?

In my Objective-C code I'd like to take a NSString value, iterate through the letters, sum ASCII values of the letters and return that to the user (preferably as the NSString too).
I have already written a loop, but I don't know how to get the ASCII value of an individual character. What am I missing?
- (NSString*) getAsciiSum: (NSString*) input {
NSInteger sum = 0;
for (NSInteger index=0; index<input.length; index++) {
sum = sum + (NSInteger)[input characterAtIndex:index];
}
return [NSString stringWithFormat: #"%#", sum];
}
Note: I've seen similar questions related to obtaining ASCII values, but all of them ended up displaying the value as a string. I still don't know how to get ASCII value as NSInteger.
Here is the answer:
- (NSString *) getAsciiSum: (NSString *) input
{
NSString *input = #"hi";
int sum = 0;
for (NSInteger index = 0; index < input.length; index++)
{
char c = [input characterAtIndex:index];
sum = sum + c;
}
return [NSString stringWithFormat: #"%d", sum]);
}
This is working for me.
Hope this helps!
This should work.
- (NSInteger)getAsciiSum:(NSString *)stringToSum {
int asciiSum = 0;
for (int i = 0; i < stringToSum.length; i++) {
NSString *character = [stringToSum substringWithRange:NSMakeRange(i, 1)];
int asciiValue = [character characterAtIndex:0];
asciiSum = asciiSum + asciiValue;
}
return asciiSum;
}
Thank you to How to convert a NSString to NSInteger with the sum of ASCII values? for the reference.

How to merge 2 NSStrings with a formatter?

Merging these two strings:
#"###.##"
#"123"
Should output:
#"1.23"
I have developed a solution for this, but I'm looking for a simpler way, Using a NSNumberFormater, or some other API that I might be missing in Apple's documentation.
Thank you!
-
The solution as is right now, that I'm trying to get rid of:
/**
* User inputs a pure, non fractional, numeric string (e.g 1234) We'll see how many fraction digits it needs and format accordingly (e.g. 1234 produces a string such as '12.34' for 2 fractional digits. 12 will produce '0.12'.)
*
* #return The converted numeric string in an instance of NSDecimalNumber
*/
- (NSDecimalNumber *)decimalNumberFromRateInput
{
if (_numericInput == nil ||
_numericInput.length == 0) {
_numericInput = #"0";
}
[self clearLeadingZeros];
if (self.formatter == nil) {
return nil;
}
if (self.formatter.maximumFractionDigits == 0) {
return [NSDecimalNumber decimalNumberWithString:_numericInput];
}
else if (_numericInput.length <= self.formatter.maximumFractionDigits) {
NSString *zeros = #"";
for (NSInteger i = _numericInput.length; i < self.formatter.maximumFractionDigits ; i++) {
zeros = [zeros stringByAppendingString:#"0"];
}
NSString *decimalString = [NSString stringWithFormat:#"0.%#%#",zeros,_numericInput];
return [NSDecimalNumber decimalNumberWithString:decimalString];
}
else {
NSString *decimalPart = [_numericInput substringToIndex: _numericInput.length - self.formatter.maximumFractionDigits];
NSString *fractionalPart = [_numericInput substringFromIndex:_numericInput.length - self.formatter.maximumFractionDigits];
NSString *decimalString = [NSString stringWithFormat:#"%#.%#", decimalPart, fractionalPart];
return [NSDecimalNumber decimalNumberWithString: decimalString];
}
}
If I understand your goal correctly, the solution should be much simpler:
float number = [originalString floatValue] / 100.0;
NSString *formattedString = [NSString stringWithFormat:#"%.2f", number];

Create string based on characters expected

I would like to create a string based on the number of characters passed in. Each character passed in will be a "X". So for example, if the length passed in is 5, then the string created should be
NSString *testString=#"XXXXX";
if it is 2 then it would be
NSString *testString=#"XX";
Can anyone tell me what the most efficient way to do this would be?
Thank you!
If you know the maximum length is some reasonable number then you could do something simple like this:
- (NSString *)xString:(NSUInteger)length {
static NSString *xs = #"XXXXXXXXXXXXXXXXXXXXXXXXXXX";
return [xs substringToIndex:length];
}
NSString *str = [self xString:5]; // str will be #"XXXXX";
If you pass in too large of a length, the app will crash - add more Xs to xs.
This approach is more efficient than building up an NSMutableString but it does make an assumption about the maximum length you might need.
- (NSString *)stringOf:(NSString *)str times:(NSInteger)count
{
NSMutableString *targ = [[NSMutableString alloc] initWithCapacity:count];
for (int i=0; i < count; i++)
{
[targ appendString:str];
}
return targ;
}
and
[self stringOf:#"X" times:4];
note that initWithCapacity: (in performance manner) better than init. But I guess that's all for efficiency.
The way I would do it is
NSMutableString *xString = [[NSMutableString alloc] init];
while ( int i = 0; i < testString.length; i++ ) {
[xString appendString:#"X"];
i++;
}
NSUInteger aLength. // assume this is the argument
NSMutableString *xStr = [NSMutableString stringWithCapacity: aLength];
for ( NSUInteger i = 0; i < aLength; i++ ) {
[xStr appendFormat:#"X"];
}
The following will do what you ask in one call:
NSString *result = [#"" stringByPaddingToLength:numberOfCharsWanted
withString:characterToRepeat
startingAtIndex:0];
where numberOfCharsWanted is an NSUInteger and characterToRepeat is an NSString containing the character.

Efficient way to generate a random alphabet string?

I want a string of all the characters of the alphabet randomized. Right now, I create a mutable array of the 26 characters, shuffle them with the exchangeObjectAtIndex: method and then add each character to a string that I return.
There has to be a better way to do this. Here is my code:
- (NSString *)shuffledAlphabet {
NSMutableArray * shuffledAlphabet = [NSMutableArray arrayWithArray:#[#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z"]];
for (NSUInteger i = 0; i < [shuffledAlphabet count]; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = [shuffledAlphabet count] - i;
int n = (random() % nElements) + i;
[shuffledAlphabet exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSString *string = [[NSString alloc] init];
for (NSString *letter in shuffledAlphabet) {
string = [NSString stringWithFormat:#"%#%#",string,letter];
}
return string;
}
Here's an efficient Fisher-Yates shuffle, adapted to your use case:
- (NSString *)shuffledAlphabet {
NSString *alphabet = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Get the characters into a C array for efficient shuffling
NSUInteger numberOfCharacters = [alphabet length];
unichar *characters = calloc(numberOfCharacters, sizeof(unichar));
[alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];
// Perform a Fisher-Yates shuffle
for (NSUInteger i = 0; i < numberOfCharacters; ++i) {
NSUInteger j = (arc4random_uniform(numberOfCharacters - i) + i);
unichar c = characters[i];
characters[i] = characters[j];
characters[j] = c;
}
// Turn the result back into a string
NSString *result = [NSString stringWithCharacters:characters length:numberOfCharacters];
free(characters);
return result;
}
This is the more efficient way to perform a correctly shuffled alphabet generation.
- (NSString *)shuffledAlphabet
{
const NSUInteger length = 'Z' - 'A' + 1;
unichar alphabet[length];
alphabet[0] = 'A';
for ( NSUInteger i = 1; i < length; i++ )
{
NSUInteger j = arc4random_uniform((uint32_t)i + 1);
alphabet[i] = alphabet[j];
alphabet[j] = 'A' + i;
}
return [NSString stringWithCharacters:alphabet length:length];
}
It uses the "inside-out" version of the Fischer Yates shuffle and avoids modula bias by generating the pseudorandom numbers with arc4random_uniform. Also, it requires a single allocation as all the permutations are performed in a temporary buffer.
Generating random numbers in Objective-C does this help?
*generate random number
*divide by 26 and take reminder
*index array[reminder]
You could pick random elements from the (remaining) alphabet while you build your string instead of shuffling it first:
NSMutableArray *alphabet = [NSMutableArray arrayWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
NSMutableString *result = [NSMutableString string];
NSUInteger numberOfLetters = alphabet.count;
for (NSUInteger i = 0; i < numberOfLetters; i++) {
int n = arc4random() % alphabet.count;
[result appendString:[alphabet objectAtIndex:n]];
[alphabet removeObjectAtIndex:n];
}
NSLog(#"%#", result);
This makes the code a bit shorter. Note also that using NSMutableString is more efficient than creating a new NSString each time a letter is added.

Resources