在不使用 c# 中的内置函数的情况下计算字符串长度

本文关键字:计算 情况下 字符串 函数 内置 | 更新日期: 2023-09-27 18:37:23

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

无法处理越界的错误索引,我不想使用 str.length 属性,也不想要 foreach 循环方法。

请帮忙

提前谢谢。

在不使用 c# 中的内置函数的情况下计算字符串长度

字符串在

C# 中不以任何特殊字符结尾。

到目前为止,我能想到的唯一方法(因为您不想使用框架函数)是访问字符串中的字符,直到它抛出IndexOutOfRangeException异常。

试试这个:(不推荐

string str = "test";
int counter = 0;
try
{
    for (int i = 0; ; i++)
    {
        char temp = str[i];
        counter++;
    }
}
catch(IndexOutOfRangeException ex)
{
}
Console.WriteLine(counter);

我在 String 中发现了一些有趣的函数.cs(反汇编):

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;
}

用法:

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
    }
}

只是好奇。不建议在实际代码中使用。最有趣的事情:以下是该wcslen函数中的注释:

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

:)

相关文章: