4 ms·
My original snippet contained: "int len = strlen(z_terminated);" I cut it before posting as I was going for compact code, not efficiency. Nits have been thro
by mcu 16y ago
My original snippet contained: "int len = strlen(z_terminated);"
I cut it before posting as I was going for compact code, not efficiency.
Nits have been throughly picked. :)
- jacquesm 16y ago> Nits have been throughly picked. :) Count on it, I am always very hesitant to post code on HN, realizing that if I'm not fresh or have tested the code that I'll be mercilessly hacked to little bits. It's fun though, I think my personal record is 5 bugs in 2 lines...
- mcu 16y agoThis is exactly why I contribute tens of thousands of lines to F/OSS projects. Your mettle has never truly been tested until you have hundreds of developers, from around the world, pointing out your idiocy in an excruciatingly specific manner. After your ego has been throughly decimated, then you can improve. This is closer to how I would do it in practice. void condense_by_removing (char *z_terminated, char char_to_remove) { char *next = z_terminated; while (1) { while (*z_terminated == char_to_remove) ++z_terminated; if (!(*next++ = *z_terminated++) ) break; } } EDIT: Fixed bug
- what 16y agoThis won't work, if the first char of z_terminated == char_to_remove. I have a similar solution farther down the page. Not many people seem to like doing it with pointer manipulation. EDIT: We should both probably add if(!char_to_remove) return; at the top since we'll get a seg fault if someone tries to be sneaky and passes the zero-terminator. And then might as well check if z_terminated is NULL while we're at it. Or is there a better way to handle it?
- deleted 16y ago[deleted]
- jacquesm 16y ago> After your ego has been throughly decimated, then you can improve. Aye... and that's when you learn. I've worked for a bit for a guy that had learned C in the 70's, best school I've had... also very painful at times.
- deleted 16y ago[deleted]
- jacquesm 16y agoApropos your first example it really was O(n^2) all the time, I just ran a bunch of tests on various optimization settings and the strlen gets called every iteration of the loop. I think you owe 'bwithe' a beer.
- mcu 16y agoYou're right, I should have left in 'int len = strlen(z_terminated);'