5

このプログラムは をスローしArrayIndexOutOfBoundExceptionます。

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

なぜそうなのですか?文字列が null で終了していない場合。文字列はC#でどのように処理されますか? string.Lengthプロパティを使用せずに長さを取得するにはどうすればよいですか? 私はここで混乱しています。

4

4 に答える 4

2

C/C++ では、文字列はcharインテリジェンスと動作のない配列 AFAIR に格納されます。したがって、そのような配列がどこかで終了していることを示すには、最後に \0 を追加する必要があります。

一方、C# では、string はコンテナー (プロパティとメソッドを持つクラス) です。補足として、インスタンス化されたオブジェクトに null を割り当てることができます。終了位置を示すために何も追加する必要はありません。コンテナがすべてを制御します。そのため、イテレータ(またはC#の列挙子)もあります。つまりforeach、 andLINQ式を使用して反復処理できるということです。

そうは言っても、次のようなコードで単純なカウンターを使用して、文字列の長さを取得できます。

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

namespace LengthOfString
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "abcde\0\0\0";
            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();
        }
    }
}
于 2015-09-25T07:33:15.643 に答える