+ 6
Code review: Secret message
The following code works, posting it here to see if it can be optimized in any form, speed, possible bugs, etc. Thank you. #include <stdio.h> #include <ctype.h> #define MAX_LEN 4096 int main() { char msg[MAX_LEN], *ptr = msg; fgets(msg, MAX_LEN, stdin); while(*ptr++ = isalpha(*ptr) ? 'z' - tolower(*ptr) + 'a': *ptr) ; fputs(msg,stdout); return 0; }
4 ответов
+ 5
If the input text is > MAX_LEN your program fails, but obviously it's not necessary to fix that for the code coach challenge. :)
I would prefer a more readable version, like `while(*ptr){ ...; ptr++; }`, but going for shortest code possible is like another challenge on top of the challenge so I'd say you passed :p (Though I suppose you could calculate 'z' + 'a' and replace the two constants with a single number!)
Good job!
+ 4
Thank you so much Schindlabua
in regards to length, you either have to set a value or do it in chunks until EOF. but really nice suggestions!
here's the modified version:
while(*ptr){
if(isalpha(*ptr))
*ptr = 219 - tolower(*ptr);
ptr++;
}
I also noticed that there was an unnecessary assignment in previous version due to ternary operator in case that the character wasn't alphabet.
Thank you again.
+ 4
Tina the conversion to lowercase could be made faster, though at the expense of readability. The tolower() function must check whether the character is alphabetic before converting. At this point you already determined that it is alphabetic, so all you need to do is set the bit that makes it lowercase.
*ptr = 219 - (*ptr|32);
+ 3
pretty amazing Brian !
I guess that would highly improve the speed. Getting rid of calling a function in a loop.
Thank you so much for pointing out that!