Why I can’t change a string to char in c shar console application

SurchyIT 0 Reputation points
2023-02-27T18:02:33.1633333+00:00

41C1A5E8-B4EA-4E00-AE71-1507C5144209

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2023-02-27T19:19:20.08+00:00

    You should read the docs for string.

    string name = "Karen";
    foreach (char c in name)
    {
        Console.WriteLine(c);
    }
    
    var firstChar = name[0];
    Console.WriteLine(firstChar);
    
    0 comments No comments

  2. Michael Taylor 61,101 Reputation points
    2023-02-27T19:32:01.8233333+00:00

    Because a string isn't a char as much as a double isn't an int. If you need a single character from a string then you need to decide which character you want and use indexing to get it.

    string name = "Bob Smith";
    char firstLetter = name[0];
    

    Taking a closer look at your code it appears you're trying to read a single character in. ReadLine returns a string. Convert.ToChar just grabs the first character from that string, assuming it isn't empty. But you are assuming that the string input is a number because you're then going to try to convert it to an int which will fail if it isn't already an int. Without clearer understanding of what you're trying to do here (and this looks like homework so it is unclear how far into the material you are), it would be easier to just read in the string and convert it to an integer (safely). Then work with the int directly. You don't need characters here.

    string input = Console.ReadLine();
    int zhmara;
    if (Int32.TryParse(input, out zhmara))
    {
       //zhmara is the integral value of the input, do your work now
    };
    

    Another issue I see is that you're building up a string in your loop. You then print out the string. But the next line you're trying to convert the string to a char. Why are you doing this?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.