How can we find length of a string without the help of length method of string
How can we find length of a string without the help of length method of string in C# ?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jul 29, 2012, 12:38 AM EDT
A more elegant way would be to use pointers but, as you wouldn't even be asking the question if you knew about these, then I won't elaborate further.
Shubham SrivastavaRank #290 · 8.7K reputationPosted Jul 31, 2012, 7:02 PM EDT
VulpesRank #55 · 29.2K reputationPosted Aug 1, 2012, 12:21 AM EDT
You'll need to compile with the /unsafe switch.
This works because, although you're not normally aware of it, all strings in .NET are stored in memory with a terminating null character '\0'. So, all you need to do is to keep incrementing the pointer until the null character is reached.
Notice though that, if the string actually contains a null character, then this approach will give an answer which is too small. The 'crude' method doesn't suffer from this problem.