473,799 Members | 3,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

trim 0s

Can anyone suggest a nice way to trim any leading zeros off of a string,
e.g., I'd like to take a string like 00000012 and convert it to 12.

Ta

pemo
Nov 15 '05
22 2118
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a string,
e.g., I'd like to take a string like 00000012 and convert it to 12.


sprintf(s, "%ld", atol(s));

That assumes there are nothing more than the number itself in the
string, otherwise perhaps a loop with strtok to convert each "word" in
the string separately can to the trick. Simply convert every word that
starts with '0', and just strcpy the rest.
-+-Ben-+-
Nov 15 '05 #11
On Sat, 24 Sep 2005 00:02:22 +0200, Ben Hetland
<be***********@ sintef.no> wrote in comp.lang.c:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a string,
e.g., I'd like to take a string like 00000012 and convert it to 12.
sprintf(s, "%ld", atol(s));


....assuming you don't mind potential undefined behavior.
That assumes there are nothing more than the number itself in the
string, otherwise perhaps a loop with strtok to convert each "word" in
the string separately can to the trick. Simply convert every word that
starts with '0', and just strcpy the rest.


Never use (or recommend, especially in this group), the ato...
conversion functions. They are old dangerous hacks, and produce
undefined behavior if the result of the conversion is outside the
range of the destination type.

The original language standard introduced the strto... functions, also
prototyped in <stdlib.h>, that have fully defined behavior for any
input other than a null pointer. And they provide for error checking
as well.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #12
Jack Klein wrote:
Never use (or recommend, especially in this group), the ato...
conversion functions. They are old dangerous hacks, and produce
undefined behavior if the result of the conversion is outside the
range of the destination type.


Yes, thank you for pointing that out!
I stand corrected!

But error checking is not quite trivial with these functions either, and
I find perhaps something like the following function a bit more
convenient in many cases (for base 10 only):

bool str_to_long_che cked( const char* s, long *n )
{
long v;
char *st = 0;
errno = 0;
v = strtol(s, &st, 10);
if (st == s || errno != 0 || (st && *st=='\0'))
return false;
*n = v;
return true;
}
BTW, what's the "new" strto... equivalent of the "old" atof function then?
-+-Ben-+-
Nov 15 '05 #13

"Ben Hetland" <be***********@ sintef.no> wrote in message
news:43******** ******@sintef.n o...

BTW, what's the "new" strto... equivalent of the "old" atof function then?


strtod()

-Mike
Nov 15 '05 #14
Christopher Benson-Manica wrote:
S.Tobias <si***@famous.b edbug.pals.inva lid> wrote:
pemo <us***********@ gmail.com> wrote:
Can anyone suggest a nice way to trim any leading zeros off of a string,
e.g., I'd like to take a string like 00000012 and convert it to 12.

strspn(..., "0") ?


size_t loc=strspn( mystring, "0" );
memmove( mystring, mystring+loc, strlen(mystring +loc)+1 );


And what if the number is 0?

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Nov 15 '05 #15
Zara wrote:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a string,
e.g., I'd like to take a string like 00000012 and convert it to 12.

Ta

pemo

char *s_ini="0000001 2";
char *s_final=s_ini;
while (*s_final=='0') s_final++;


Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini[i] == '0'; i++) if (s_ini[i] == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini[i];

Of course I am waiting for someone (you know who you are) to tell me
that "0" is an illegal string ...

--
Paul Hsieh
http://www.pobox.com/qed/
http://bstring.sf.net/

Nov 15 '05 #16
we******@gmail. com wrote:
Christopher Benson-Manica wrote:
S.Tobias <si***@famous.b edbug.pals.inva lid> wrote:
> pemo <us***********@ gmail.com> wrote:
> > Can anyone suggest a nice way to trim any leading zeros off of a string,
> > e.g., I'd like to take a string like 00000012 and convert it to 12.

> strspn(..., "0") ?


size_t loc=strspn( mystring, "0" );
memmove( mystring, mystring+loc, strlen(mystring +loc)+1 );


And what if the number is 0?

Who said anything about numbers? The OP only wanted to remove
all initial zeroes from a string. :)
http://dspace.dial.pipex.com/town/gr.../bloopers.html
"This is a lovely picture ..." is very adequate here.

Seriously, I'm sure the OP has already discovered by now
what he really needed.

--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 15 '05 #17
websn...@gmail. com wrote:
Zara wrote:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a
string, e.g., I'd like to take a string like 00000012 and convert
it to 12.


char *s_ini="0000001 2";
char *s_final=s_ini;
while (*s_final=='0') s_final++;


Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini[i] == '0'; i++) if (s_ini[i] == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini[i];


Huh? Zara's version is far better than yours, by any yardstick.
You can't write stuff like this and then expect people to not
think you are a troll...

Nov 15 '05 #18
Old Wolf wrote:
websn...@gmail. com wrote:
Zara wrote:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a
string, e.g., I'd like to take a string like 00000012 and convert
it to 12.

char *s_ini="0000001 2";
char *s_final=s_ini;
while (*s_final=='0') s_final++;
Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini[i] == '0'; i++) if (s_ini[i] == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini[i];


Huh? Zara's version is far better than yours, by any yardstick.


Really? I pick correctness as my yardstick. Try setting s_ini =
"0000"; and compare the two solutions.
You can't write stuff like this and then expect people to not
think you are a troll...


Oh yeah, I forgot "correctnes s" is off topic here in CLC. If the
solution doesn't obsess over some standards minutia it must be a troll.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Nov 15 '05 #19
we******@gmail. com wrote:
Old Wolf wrote:
websn...@gmail. com wrote:
Zara wrote:
pemo wrote:
> Can anyone suggest a nice way to trim any leading zeros off of a
> string, e.g., I'd like to take a string like 00000012 and convert
> it to 12.

char *s_ini="0000001 2";
char *s_final=s_ini;
while (*s_final=='0') s_final++;

Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini[i] == '0'; i++) if (s_ini[i] == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini[i];
Huh? Zara's version is far better than yours, by any yardstick.


Really? I pick correctness as my yardstick. Try setting s_ini =
"0000"; and compare the two solutions.


Both solutions give "" in that case. Zara's is easier to read by far.
Oh yeah, I forgot "correctnes s" is off topic here in CLC. If
the solution doesn't obsess over some standards minutia it
must be a troll.


Replacing a short one-liner with a 4 lines that do exactly the
same thing in a more inefficient and obfuscated way... troll.

I suspect you are going to say that you think "0000" with leading
zeroes removed is "0", and you also planned to write a program
that gives "0", but you accidentally wrote a program that gives "".

I think this just proves the point that the shorter, clearer
solution is less prone to errors (and that you should indent
your code properly).

But even then, you would have to say that "2222" with leading
2s removed is "2", and " \t" with leading whitespace removed
is "\t", which is something that I think most people would
disagree with. Unless you think '0' is some sort of special
character?

Nov 15 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
12767
by: Simon | last post by:
Hi, I have written a function to trim char *, but I have been told that my way could be dangerous and that I should use memmove(...) instead. but I am not sure why my code could be 'dangerous' or even why there could be a problem. here is the code ////////
5
33336
by: Alex Vassiliev | last post by:
Hi all. Just wanted to share two handy RegEx expressions to strips leading and trailing white-space from a string, and to replace all repeated spaces, newlines and tabs with a single space. * JavaScript example: String.prototype.trim = function() { // Strip leading and trailing white-space
12
47962
by: Robert Mark Bram | last post by:
Hi All, I am using the following trim function: function trim (str) { return str.replace(/^\s*/g, '').replace(/\s*$/g, ''); } The problem is that this doesn't trim instances of the "&nbsp;" char - the non breaking space. Can this be represented in a grep statement at
3
2750
by: FlyerN87 | last post by:
For some reason this command will not trim the names shown in the fields listed. I'm trying to do this in a text box on a report. I've done this fairly succesfully in other reports but I must have done something wrong here.... I've tried both of these... =Trim( & ) =Trim( &", "& )
11
5359
by: Darren Anderson | last post by:
I have a function that I've tried using in an if then statement and I've found that no matter how much reworking I do with the code, the expected result is incorrect. the code: If Not (strIn.Substring(410, 10).Trim = "") Then 'Something processed Else 'Something processed
7
4225
by: Sascha Herpers | last post by:
Hi, what is the difference between the trim function and the trim String-member? As far as I see it, both return the trimmed string and leave the original string unaltered. Is any of the two faster? Is there a general rule/opinion to prefere members over functions? Thanks for any hint.
22
9756
by: Terry Olsen | last post by:
I have an app that makes decisions based on string content. I need to make sure that a string does not contain only spaces or newlines. I am using the syntax 'Trim(String)" and it works fine. I thought I'd change it to the VB ..NET method "String.Trim" but that throws an object exception. Which brings the question: is it compliant to use Trim(String), or is it more within etiquette to use If Not String Is Nothing Then String.Trim?
1
20672
by: arsaral | last post by:
Hi, Here is an extension of MSDN's trim right example to trim left-right... First subroutines then the calling structure is given below... Cheers. Ali Riza SARAL //*************************************************************
31
2926
by: rkk | last post by:
Hi, I've written a small trim function to trim away the whitespaces in a given string. It works well with solaris forte cc compiler, but on mingw/cygwin gcc it isn't. Here is the code: char *trim(char *s) { char *begin,*end; begin = s;
8
3266
by: Keith Thompson | last post by:
Kevin Smith <no@spam.comwrites: You posted this to microsoft.public.dotnet.languages.csharp, where I presume it's topical. Why on Earth did you redirect followups to comp.lang.c? Anyone else replying to Kevin Smith's article, please *ignore* the Followup-To header and post only to the csharp group. Thanks.
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10260
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7570
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.