views:

127

answers:

4

I have a string 0023525631 but what I want is the string 23525631 without the leading zeroes.

How do I do this; I am confused about it.

+3  A: 

You can convert string to integer and integer to string if you are number.

Or

Declarate pointer to this string and set this pointer to a start of your string, then iterate your string and add to this pointer number of zeros on the start of string. Then you have pointer to string who starting before zeros, you must use pointer to obitain string without zeros, if you use string you can get string with zeros.

Or

You can reverse string, and iterate it from reverse, if you get some char != '0' you stop iterating else you rewriting this char to null. After it you can reverse string to get back your integer in string without leading zeros.

Svisstack
why do you need to reverse string, I think a forward iteration will be better? You can just iterate and if you meet 0, remove, not 0, stop?
vodkhang
@vodkhang: No because you can't set null at start of your string. And with reverse, lenght of string was changed (in second reverse) because second reverse get smaller iteration (depends on how many nulls was writed)
Svisstack
@vodkhand: you dont must reverse your string but you must use other moved pointer to your string (moved to right depends on number of zeros)
Svisstack
@vodkhand: i added for you other solution
Svisstack
Converting the String(00123456525) into int really did the tridck for me thanks a lot ...
mrugen
A: 

You can use:

temp = @"0023525631";

temp = [temp stringByReplacingOccurrencesOfString:@"0" withString:@""];

kool4u
here temp is an NSString object.
kool4u
You're assuming that he also wants to remove 0's from elsewhere in the string too, not just at the beginning. The questioner didn't make it clear if that's what he wanted or not...
Jasarien
From his question it seems that he only wants to remove 0's from his string...
kool4u
i want remove 0 only from beginning only
mrugen
The point, kool4u, is zeros in the *middle* of the string will also be removed.
Joshua Nozzi
+3  A: 

I'm assuming here that you only want to remove the leading zeros. I.E. @"*00*1234*0*56" becomes @"1234*0*56", not @"123457". To do that, I'd use an NSScanner.

// String to strip
NSString *test = @"001234056";

// Skip leading zeros
NSScanner *scanner = [NSScanner scannerWithString:test];
NSCharacterSet *zeros = [NSCharacterSet
                            characterSetWithCharactersInString:@"0"];
[scanner scanCharactersFromSet:zeros intoString:NULL];

// Get the rest of the string and log it
NSString *result = [test substringFromIndex:[scanner scanLocation]];
NSLog(@"%@ reduced to %@", test, result);
Will Harris
+3  A: 

This is exactly the kind of thing NSNumberFormatter is made for (and it's way better at it). Why reinvent the wheel?

Joshua Nozzi