I don't think I've ever written code to do that outside of homework assignments and interviews.
I don't think I've ever written code to do that outside of homework assignments and interviews.
[1]: I'm leaving "characters" undefined here, because no matter what Unicode-aware definition you apply here, you've got trouble.
Well there's your problem right there...
"The user sent me a form submission with 150. I need to do something to resolve that."
Any software that defines "do something" here as "silently discard 1/3rd of the user input" is software I'm going to throw in the trash. If you must have fixed-length fields, surely telling the user "much characters, wow overflow" is better than just chopping the input.
The point that when you're worrying about string length, it's often an indicator of a separate problem is a good one. But some things really do need the ability to measure/truncate strings and not every situation allows just throwing the software in the trash as an option.
"Any software that defines "do something" here as "silently discard 1/3rd of the user input" is software I'm going to throw in the trash."
You are reading far more in than I put in. I merely said somehow you need to resolve this; you put a particular resolution in my mouth, then attacked.
I did choose the web for one reason, which is that you can't avoid this case; you can try to limit the UI to generating 100 characters only (and I still haven't defined "characters"...), but it's 15 seconds for a user to pull open Firebug and smash 150 characters into your form submission anyhow. Somehow, you better resolve this, and as quickly as you mounted the high horse when faced with the prospect of mere truncation, throwing the entire request out for that will cause somebody else to mount an equally high horse....
Maybe someone decided 100 characters was a reasonable cutoff and that field is not important enough to reject (read: increase bounce rate) on if someone manages to send too much.
Maybe the 100 characters is a short string generated from an unrestricted long string and cached on a separate server.
I admit it's dirty but it was throwaway code for an isolated case.
Edit: eh, guys, as I stated the string came from a binary dump. I didn't get to choose the encoding, it came from ROM in an embedded system with a different Endianness. I had to figure out a way to make it human readable.
Think in the lines of python's:
>>> 'abcd'[:-1]
'abc'