How do strings end in C #?

This program throws ArrayIndexOutOfBoundException.

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

Why is that? If the lines do not have a zero ending. How are strings handled in C #? How to get length without using property string.Length? I'm confused here.!

+4
source share
4 answers

C # does not use complete NUL strings, as C and C ++ do. You must use the property Lengthfor the string.

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

or using formatters

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

// prints Naveen

+2
source

, name. :

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

# this . name.Length

: , @NaveenKumarV , \0, , ToCharArray. :

var result = name.ToCharArray().TakeWhile(i => i != '\0').ToList();
+1

C/++ char AFAIR . , , -, \0 .

, # - ( ); , null . , , . . , ( #, ). , foreach LINQ .

, , , :

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();
        }
    }
}
+1

Source: https://habr.com/ru/post/1608933/


All Articles