How To Convert A Number To an ASCII Character?

后端 未结 6 1177
礼貌的吻别
礼貌的吻别 2020-12-17 09:45

I want to create an application where user would input a number and the program will throw back a character to the user.

Edit: How about vice versa, changing a ascii

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 10:21

    Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), chars are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.

    // Read a line of input
    string input = Console.ReadLine();
    
    int value;
    // Try to parse the input into an Int32
    if (Int32.TryParse(input, out value)) {
        // Parse was successful
        if (value >= 0 and value < 128) {
            //value entered was within the valid ASCII range
            //cast value to a char and print it
            char c = (char)value;
            Console.WriteLine(c);
        }
    }
    

提交回复
热议问题