how to get digits of a integer from NSString? - iphone

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--;
}

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!

hex a to binary

i am trying to convert my hex value to binary value , but i am facing little problem .
as i am new trying to learn my faults .
my code :
NSMutableString *str;
NSString *dd = #"192:168:1:2:0B:2:D:00";
NSCharacterSet *donotwant1 = [NSCharacterSet characterSetWithCharactersInString:#":""];
dd =[[dd componentsSeparatedByCharactersInSet:donotwant1] componentsJoinedByString:#" "];
NSMutableArray *array = [[dd componentsSeparatedByString:#" "] mutableCopy];
[array removeObjectAtIndex:0];
//NSLog(#"%#",array);
for (int j=0; j<[array count]; j++) {
NSScanner *scan = [NSScanner scannerWithString:[array objectAtIndex:j]];
unsigned int i=0;
if ([scan scanHexInt:&i]) {
// NSLog(#"numbner is %ustr", i);
}
NSInteger theNumber = i;
str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1) {
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
[array removeObjectAtIndex:j];
[array insertObject:str atIndex:j];
}
}
NSLog(#"Binary version: %#", array);
I'm getting
1,1100,11001111,1111,1111,11101111.....
in my code 0 values are eliminated . i want 8bits like(00000001,00001100.....) can any one tell me the reason
When the most significant bit is reached, your algorithm stops the conversion. Why not force the loop to always execute 8 times?
for (int numberCopy = theNumber, int i = 0; i < 8; numberCopy >>= 1, i++) {
// loop body here
}
By the way, here's a cleaner/shorter/simpler approach that doesn't involve highly superfluous copying and uses characters instead of string objects for hyper efficiency (just kidding, I'm all against micro-optimizations, but I feel like inserting an NSString before another one is unnecessary, especially if the number of bits is known and constant). This also assumes UTF-8 and exploits the fact that hexadecimal and binary representation have a very nice relationship, 16 being the 4th power of 2:
NSString *dd = #"01:0C:CF:0F:EF:AF:BD:00";
NSArray *bytes = [dd componentsSeparatedByString:#":"];
NSMutableArray *binaries = [NSMutableArray array];
NSString *lookup[256];
lookup['0'] = #"0000";
lookup['1'] = #"0001";
lookup['2'] = #"0010";
lookup['3'] = #"0011";
lookup['4'] = #"0100";
lookup['5'] = #"0101";
lookup['6'] = #"0110";
lookup['7'] = #"0111";
lookup['8'] = #"1000";
lookup['9'] = #"1001";
lookup['A'] = #"1010";
lookup['B'] = #"1011";
lookup['C'] = #"1100";
lookup['D'] = #"1101";
lookup['E'] = #"1110";
lookup['F'] = #"1111";
for (NSString *s in bytes) {
unichar n1 = [s characterAtIndex:0];
unichar n0 = [s characterAtIndex:1];
[binaries addObject:[lookup[n1] stringByAppendingString:lookup[n0]]];
}
NSLog(#"%#", binaries);

how to add comma to string after every nth character in xcode

my problem is pretty simple. I assign a value to string variable in xcode which looks like this:
ARAMAUBEBABRBGCNDKDEEEFO
and I need it like this:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO
The length is different in each variable.
thanx in advance
This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps.
//add comas to a a string...
//example1: #"5123" = #"5,123"
//example2: #"123" = #"123"
//example3: #"123123123" = #"123,123,123"
-(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{
NSMutableString *stringFormatted = [NSMutableString stringWithFormat:#"%#",myString];
for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) {
if (i>0) {
[stringFormatted insertString: #"," atIndex: i];
}
}
return stringFormatted;
}
Try this:
int num;
NSMutableString *string1 = [NSMutableString stringWithString: #"1234567890"];
num = [string1 length];
for(int i=3;i<=num+1;i++) {
[string1 insertString: #"," atIndex: i];
i+=3;
}
NSString *yourString; // the string you want to process
int len = 2; // the length
NSMutableString *str = [NSMutableString string];
int i = 0;
for (; i < [yourString length]; i+=len) {
NSRange range = NSMakeRange(i, len);
[str appendString:[yourString substringWithRange:range]];
[str appendString:#","];
}
if (i < [str length]-1) { // add remain part
[str appendString:[yourString substringFromIndex:i]];
}
// str now is what your want
This would work well when your string is not very large:
NSString * StringByInsertingStringEveryNCharacters(NSString * const pString,
NSString * const pStringToInsert,
const size_t n) {
NSMutableString * const s = pString.mutableCopy;
for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) {
[s insertString:pStringToInsert atIndex:pos];
}
return s.copy;
}
If the string is very large, you should favor to compose it without insertion (append-only).
(define your own error detection)

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;
}

NSString range of string at occurrence

i'm trying to build a function that will tell me the range of a string at an occurrence.
For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.
I've tried building this simple function, but it doesn't work.
Note - the top functions were constructed at an earlier date and work fine.
Any help appreciated.
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex {
if (toCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = 0; i <= toCharacterIndex; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex {
if (fromCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = (fromCharacterIndex+1); i <= [stringToTrim length]; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence {
NSString *trimmedString = [inString copy]; //We start with the whole string.
NSUInteger len, loc, oldLength;
len = 0;
loc = 0;
NSRange tempRange = [string rangeOfString:substring];
len = tempRange.length;
loc = tempRange.location;
for (int i = 0; i != occurence; i++) {
NSUInteger endOfWord = len+loc;
trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord];
oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length];
NSRange tmp = [trimmedString rangeOfString:substring];
len = tmp.length;
loc = tmp.location + oldLength;
}
NSRange returnRange = NSMakeRange(loc, len);
return returnRange;
}
Instead of trimming the string a bunch of times (slow), just use rangeOfString:options:range:, which searches only within the range passed as its third argument. See Apple's documentation.
So try:
- (NSRange)rangeOfString:(NSString *)substring
inString:(NSString *)string
atOccurence:(int)occurence
{
int currentOccurence = 0;
NSRange rangeToSearchWithin = NSMakeRange(0, string.length);
while (YES)
{
currentOccurence++;
NSRange searchResult = [string rangeOfString: substring
options: NULL
range: rangeToSearchWithin];
if (searchResult.location == NSNotFound)
{
return searchResult;
}
if (currentOccurence == occurence)
{
return searchResult;
}
int newLocationToStartAt = searchResult.location + searchResult.length;
rangeToSearchWithin = NSMakeRange(newLocationToStartAt, string.length - newLocationToStartAt);
}
}
You need to rework the whole code. While it may seem to work, it's poor coding and plain wrong, like permanently reassigning the same variable, initializing but reassigning one line later, releasing after returning (which will never work).
For your question: Just use rangeOfString:options:range:, and do this the appropriate number of times while just incrementing the starting point.