left( source, count ) in C
Dave Kirsch
a563 at mindlink.UUCP
Sat Mar 17 01:54:50 AEST 1990
> nacer writes:
>
> Msg-ID: <510007 at 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 at mindlink.UUCP
Vancouver, British Columbia
More information about the Comp.lang.c
mailing list