3
Answers

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# ?

Answers (3)

0
Photo of Vulpes
NA 98.3k 1.5m 12y
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
Photo of Vulpes
NA 98.3k 1.5m 12y
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
Photo of Shubham Srivastava
NA 8.6k 1.7m 12y
Hi Vulpes, Give me the second way to get the length of string using pointer.