Archna Saini
Archna Saini

Reputation: 29

Calculating string length without using inbuilt function in c#

 string str = "test";
 int counter = 0;
 for (int i = 0; str[i] != '\n'; i++)
 {
    counter++;
 }

Unable to handle error index out of bound and I don't want to use the str.length property and also don't want foreach loop approach.

Please help

Thanks in advance.

Upvotes: 0

Views: 1338

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

strings does not end with any special character in c#.

the only way i can think as of now for your requirement(as you don't want to use Framework functions) is accessing the characters in the string untill it throws the IndexOutOfRangeException Exception.

Try This: (not recommended)

string str = "test";
int counter = 0;

try
{
    for (int i = 0; ; i++)
    {
        char temp = str[i];
        counter++;
    }
}
catch(IndexOutOfRangeException ex)
{
}

Console.WriteLine(counter);

Upvotes: 3

user2160375
user2160375

Reputation:

I've found some interesting function inside String.cs (disassembled):

private static unsafe int wcslen(char* ptr)
{
    char* end = ptr;
    while (((uint)end & 3) != 0 && *end != 0)
        end++;
    if (*end != 0)
    {
        while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0))
        {
            end += 2;
        }
    }
    for (; *end != 0; end++)
        ;

    int count = (int)(end - ptr);

    return count;
}

usage:

class Program
{
    private static void Main(string[] args)
    {
        var a = "asample";

        unsafe
        {
            fixed (char* str_char = a)
            {
                var count = wcslen(str_char);
            }
        }
    }

    private static unsafe int wcslen(char* ptr)
    {
      // impl
    }
}

Just curiosity. Not recommended in real code. The most interesting thing: Here is comment inside that wcslen function:

// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.

:)

Upvotes: 0

Related Questions