1. 请写一个函数,计算字符串的长度.
答:
int strlen(const char* src){
    assert( NULL != src);
    
    int len = 0;
    while(*src++ != '\0')
       len++;
    
    return len;
}现在要求把这个函数变成C#的(不得使用类库)

解决方案 »

  1.   

    不使用length的话,好难想,真期待高手来回答
      

  2.   

    搞个弱智的哈~string str = "hello";
    int i = -1;
    while(true) {
        try {
           str[++i];
        }catch(IndexOutOfRangeException) {
            break;
        }
    }
    return i;
      

  3.   

    int strlen(string src)
            {
                int len = 0, i=0;
                byte[] chStr =  Encoding.ASCII.GetBytes( src );
                try
                {
                    while (chStr[i++] != '\0')
                        len++;
                }
                catch { }
                return len;
            }
      

  4.   

    变态要求!C#不是C!
    C#不使用类库寸步难行~
      

  5.   

    很简单啊,加上unsafe关键字就行啦! unsafe int strlen(char* src)
    {
    System.Diagnostics.Debug.Assert(null != src); int len = 0;
    while (*src++ != '\0')
    len++; return len;
    }
      

  6.   

    重新加工了一下,现在更完善了:static unsafe int strlen(string src)
    {
    System.Diagnostics.Debug.Assert(null != src); int len = 0; fixed (char* pSrc = src)
    {
    char* p = pSrc;
    while (*p++ != '\0')
    len++;
    } return len;
    }