Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing leading zeroes from a string

I have a string 0023525631 but what I want is the string 23525631 -- without the leading zeroes. How do I do this?

like image 749
mrugen munshi Avatar asked Sep 07 '10 10:09

mrugen munshi


People also ask

How do you remove leading zeros from a string?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. The ^0+(?! $)"; To remove the leading zeros from a string pass this as first parameter and “” as second parameter.

How do you remove leading zeros from a string in C++?

str. erase(0, min(str. find_first_not_of('0'), str. size()-1));

How do you remove leading zeros from a string in Python?

Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python. The lstrip() can be utilized to remove the leading characters of the string if they exist. By default, a space is the leading character to remove in the string.

How do you remove preceding zeros in Java?

Approach: We use the StringBuffer class as Strings are immutable. Count leading zeros by iterating string using charAt(i) and checking for 0 at the “i” th indices. Use StringBuffer replace function to remove characters equal to the above count using replace() method.


2 Answers

Use Reguler Expression like this,

 NSString *str =@"000034234247236000049327428900000";
    NSRange range = [str rangeOfString:@"^0*" options:NSRegularExpressionSearch];
    str= [str stringByReplacingCharactersInRange:range withString:@""];
    NSLog(@"str %@",str);

O/P:-str 34234247236000049327428900000

like image 161
Balu Avatar answered Oct 03 '22 04:10

Balu


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.

like image 35
Svisstack Avatar answered Oct 03 '22 05:10

Svisstack