字符串如何在 C# 中终止?

How are strings terminated in C#?

此程序抛出 ArrayIndexOutOfBoundException

string name = "Naveen";
int c = 0;
while( name[ c ] != '[=10=]' ) {
    c++;
}
Console.WriteLine("Length of string " + name + " is: " + c);

为什么会这样? 如果字符串不是空终止的。在 C# 中如何处理字符串? 如何在不使用 string.Length 属性 的情况下获取长度? 我在这里很困惑。!

您正在尝试访问索引处的字符,根据 name 长度,该索引不可用。你可以这样解决:

string name = "Naveen";    
int c = 0;
while (c < name.Length)
{
    c++;
}

However there is no need to count the length of a string in c# this way. You can try simply name.Length

编辑: 根据@NaveenKumarV 在评论中提供的内容,如果您想检查 [=14=] 个字符,那么正如其他人所说,您可以尝试 ToCharArray 方法.这是代码:

var result = name.ToCharArray().TakeWhile(i => i != '[=11=]').ToList();

C# 不像 C 和 C++ 那样使用以 NUL 结尾的字符串。您必须使用字符串的 Length 属性。

Console.WriteLine("Length of string " + name + " is: " + name.Length.ToString());

或使用格式化程序

Console.WriteLine("Length of string '{0}' is {1}.", name, name.Length);  
 public static void Main()
 {
     unsafe
     {
         var s = "Naveen";
         fixed (char* cp = s)
         {
             for (int i = 0; cp[i] != '[=10=]'; i++)
             {
                 Console.Write(cp[i]);
             }
         }
     }
 }

// 打印 Naveen

在 C/C++ 中,字符串存储在 char 数组 AFAIR 中,没有智能和行为。因此,为了表明这样的数组在某处结束,必须在末尾添加 \0。

另一方面,在C#中,字符串是一个容器(一个class有属性和方法);作为旁注,您可以将 null 分配给它的实例化对象。您不需要向它添加任何内容来指示它的结束位置。容器为您控制一切。因此,它也有迭代器(我认为是 C# 中的枚举器)。这意味着您可以使用 foreachLINQ 表达式对其进行迭代。

话虽如此,您可以在与此类似的代码中使用一个简单的计数器来获取字符串的长度:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LengthOfString
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "abcde[=10=][=10=][=10=]";
            Console.WriteLine(s);
            Console.WriteLine("s.Length = " + s.Length);
            Console.WriteLine();

            // Here I count the number of characters in s
            // using LINQ
            int counter = 0;
            s.ToList()
                .ForEach(ch => {
                    Console.Write(string.Format("{0} ", (int)ch));
                    counter++;
                });
            Console.WriteLine(); Console.WriteLine("LINQ: Length = " + counter);
            Console.WriteLine(); Console.WriteLine();

            //Or you could just use foreach for this
            counter = 0;
            foreach (int ch in s)
            {
                Console.Write(string.Format("{0} ", (int)ch));
                counter++;
            }
            Console.WriteLine(); Console.WriteLine("foreach: Length = " + counter);

            Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine();
            Console.WriteLine("Press ENTER");
            Console.ReadKey();
        }
    }
}