0

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 ?

7
  • 8
    A char array is not a string. A string is a string. And strings in C# are not null terminated. And Length is not a function, and it is O(1) to compute, not O(n). I suspect you are a C programmer; remember, C# is a different language. Commented Jul 14, 2013 at 15:02
  • 2
    Btw why do you want to do that Commented Jul 14, 2013 at 15:05
  • "without using the built in functions" why? Commented Jul 14, 2013 at 15:10
  • @Eric: How is it "not a function"? It's a property getter method, which will be inlined, but it's still a method. Commented Jul 14, 2013 at 15:10
  • @BenVoigt: array lengths are generated using the ldlen instruction, not a method invocation. Commented Jul 14, 2013 at 16:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it be i < str.Length.. ?
Yeah, forgot it; Thanks!
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.