Re: [SPOILER] Solution to Perl 'Easy' Quiz #2005-2
Shlomi Fish <shlomif-ik1l9ssToec+JF/[email protected]> Sat, 5 Feb 2005 19:58:26 +0200
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
On Saturday 05 February 2005 19:10, Brad Greenlee wrote:
> sub t_inline_c {
> use Inline C => <<'[END]';
>
> char* rmdots_c(char* str) {
> char* newstr = malloc(strlen(str));
>
I think this should be strlen(str)+1. The memory occupied by the string is its
length + 1 for the trailing NULL character. (\0).
> /* find rightmost dot in string */
> int i = 0;
> int j = 0;
> int rdot = -1;
> int numdots = 0;
> while (str[i]) {
> if (str[i] == '.') {
> rdot = i;
> numdots++;
> }
> else {
> newstr[j++] = str[i];
> }
> i++;
> }
> if (!numdots) { return str; } /* no dots, so we're done */
>
> /* copy string from rightmost dot on */
> strcpy(newstr + rdot - (numdots - 1), str + rdot);
>
> return newstr;
>
> /* or we could play nice and do this, which is slower:
> return realloc(newstr, j);
> */
> }
> [END]
>
> return rmdots_c($_[0]);
> }
>
Nice way to do it in C.
Regards,
Shlomi Fish
---------------------------------------------------------------------
Shlomi Fish shlomif-ik1l9ssToec+JF/[email protected]
Homepage: http://www.shlomifish.org/
Knuth is not God! It took him two days to build the Roman Empire.