0
 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.

10
  • 1
    Interview question ...sir Commented Jan 14, 2015 at 7:30
  • 1
    so what's the alternative?? Commented Jan 14, 2015 at 7:31
  • 1
    why not inbuilt function? Commented Jan 14, 2015 at 7:31
  • 2
    Strings are not terminated by any special symbol in C# so this approach will not work. Commented Jan 14, 2015 at 7:32
  • 1
    Actually it is possible in c that's why I am thinking would it be possible in c#?? Commented Jan 14, 2015 at 7:35

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

:)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.