Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!philmtl!atha!aunro!alberta!ubc-cs!van-bc!rsoft!mindlink!a563 From: a563@mindlink.UUCP (Dave Kirsch) Newsgroups: comp.lang.c Subject: Re: left( source, count ) in C Message-ID: <1325@mindlink.UUCP> Date: 16 Mar 90 15:54:50 GMT Organization: MIND LINK! - British Columbia, Canada Lines: 39 > nacer writes: > > Msg-ID: <510007@hpmcaa.mcm.hp.com> > Posted: 16 Mar 90 17:55:54 GMT > > Org. : HP McMinville Division > Person: Abdenacer Moussaoui > > How do you write a function that returns the left part of a string in C? > > The interface is left( source, count ) here are some test cases: > > left( "123456789", 3 ) returns "123" > left( "123456789", 20 ) returns "123456789" > > if stimef( current_time ) returns "13:45:23:48" > then left( stimef( current_time ), 8 ) returns "13:45:23" > > As you can see in the last case, I would't want left(,) to modify the source > (ie. implementing left something like source[count] = '\0' ) > Thanks for any info. Try this [note that it is this function uses a static buffer that is overwritten on each call, so save the results before you call it again]: char *left(const char *source, int count) { static char st[81]; /* Increase this as required */ strncpy(st, source, count); st[count] = 0; /* Shorten it. */ return st; /* And return it. */ } -- _____________________________________________________________________ Dave Kirsch UUCP: {uunet,ubc-cs}!van-bc!rsoft!mindlink!a563 Voice: (604) 327-4404 a563@mindlink.UUCP Vancouver, British Columbia