krrishna
krrishna

Reputation: 2078

How to read characters of string or character array without using length function

I want to read all the characters from the string without using the built in functions.I tried the below.

        char[] str ={ 'k','r','i','s'};            
        for ( int i = 0; str[i]!='\0'; i++)
        {
            Console.WriteLine(str[i]);
        }

But I get an exception because unlike in c I don't see the string here ends with a null character. Is there any other way (apart from using built functions/try catch block in case of exception) I can read all the characters of the string ?

Upvotes: 0

Views: 3158

Answers (2)

terrybozzio
terrybozzio

Reputation: 4542

If what you really want is to display the string that the characters in the char array produce:

char[] mychars = { 'k', 'r', 'i', 's' };
Console.WriteLine("Your characters form the following string: " + new string(mychars));

Upvotes: 0

Zbigniew
Zbigniew

Reputation: 27594

In c# arrays have Length property:

char[] str ={ 'k','r','i','s'};            
for (int i = 0; i < str.Length; i++)
{
    Console.WriteLine(str[i]);
}

Otherwise you can use foreach which will enumerate all characters in an array.

Upvotes: 3

Related Questions