0
Here's a rather crude way to do it:
using System;
class Test
{
static void Main()
{
string s = "Shubham";
int length = 0;
try
{
char c;
while(true)
{
c = s[length];
length++;
}
}
catch(IndexOutOfRangeException)
{
}
Console.WriteLine("The length of '{0}' is {1}", s, length);
Console.ReadKey();
}
}
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.
Accepted 0
Sure, here it is:
using System;
class Test
{
unsafe static void Main()
{
string s = "Shubham";
int length = 0;
fixed(char* ps = s)
{
char* pc = ps;
while(*pc++ != '\0') length++;
}
Console.WriteLine("The length of '{0}' is {1}", s, length);
Console.ReadKey();
}
}
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.
0
Hi Vulpes, Give me the second way to get the length of string using pointer.