a563@mindlink.UUCP (Dave Kirsch) (03/16/90)
> 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
nacer@hpmcaa.mcm.hp.com (Abdenacer Moussaoui) (03/17/90)
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' ) If this definition of left() does not fit "standard" C assumptions about strings, what how would you code left if source was restricted to type SMALL_STRINGS defined as typedef char SMALL_STRINGS[500] instead of just the (char *)? Thanks for any info. Thank you. --Abdenacer (nacer@hpmcaa.mcm.hp.COM)
henry@utzoo.uucp (Henry Spencer) (03/18/90)
In article <510007@hpmcaa.mcm.hp.com> nacer@hpmcaa.mcm.hp.com (Abdenacer Moussaoui) writes: >How do you write a function that returns the left part of a string in C? From context, it sounds like you don't want to allocate new storage, just treat the left part of the old string as if it were a string. And you specify that the old string not be modified. Sorry, you can't do this in C. A C string is a sequence of characters terminated by a NUL ('\0'). To make the left part into a string, you have to get that NUL in there somehow, either by modifying the old string or by allocating new storage (e.g. with malloc()) and building a copy there. -- MSDOS, abbrev: Maybe SomeDay | Henry Spencer at U of Toronto Zoology an Operating System. | uunet!attcan!utzoo!henry henry@zoo.toronto.edu