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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jul 29, 2012, 4:38 AM
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.
VulpesPosted Aug 1, 2012, 4:21 AM
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.
Shubham SrivastavaPosted Jul 31, 2012, 11:02 PM