c#:没有预定义函数的字符串长度

Ami*_*mar -2 c#

我正在编写一个代码来查找c#中字符串的总长度.代码如下

class Program
    {
        static void Main(string[] args)
        {
            string str = "Amit Kumar";
            int c = 0;
            for(int i = 0; str[i]!="\n"; i++)
            {

                c++;
            }
            Console.WriteLine(c);
            Console.ReadLine();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它显示!=运算符不能应用于char或字符串类型的操作数.你能解决我的问题吗?

mas*_*son 5

您无法使用!=错误中的说明将字符串与char进行比较.所以请'\n'改用.但无论如何,你的字符串不包含换行符,永远不会终止.

我们可以通过一些修改使您的代码工作.使用foreach地遍历字符串中的字符.

class Program
    {
        static void Main(string[] args)
        {
            string str = "Amit Kumar";
            int c = 0;
            foreach(char x in str)
            {
                c++;
            }
            Console.WriteLine(c);
            Console.ReadLine();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我希望这只是用于教育,因为内置函数可以告诉你字符串的长度.