String must be exactly one character long

前端 未结 4 623
耶瑟儿~
耶瑟儿~ 2021-01-29 10:07

I have what I think is an easy problem. For some reason the following code generates the exception, \"String must be exactly one character long\".

int n = 0;
for         


        
相关标签:
4条回答
  • 2021-01-29 10:52

    Since printable unicode characters can be anywhere in range from 0x0000 to 0xFFFF, your hexOutput variable can hold more than one character - this is why error is thrown. Convert.ToChar(string) would always check length a of string, and if it is not equal to 1 - it would throw. So it would not convert string 0x30 to hexadecimal number, and then to ascii representation, symbol 0.

    Can you elaborate on what you are trying to archieve ?

    0 讨论(0)
  • 2021-01-29 10:57

    Convert.ToChar( string s ), per the documentation requires a single character string, otherwise it throws a FormatException as you've noted. It is a rough, though more restrictive, equivalent of

    public char string2char( string s ) { return s[0] ; }

    Your code does the following:

    • Iterates over all the characters in some enumrable collection of characters.
    • For each such character, it...
      • Converts the char to an int. Hint: a char is an integral type: its an unsigned 16-bit integral value.
      • converts that value to a string containing a hex representation of the character in question. For most characters, that string will be at least two character in length: for instance, converting the space character (' ', 0x20) this way will give you the string "20".
      • You then try to convert that back to a char and replace the current item being iterated over. This is where your exception is thrown. One thing you should note here is that altering a collection being enumerated is likely to cause the enumerator to throw an exception.

    What exactly are you trying to accomplish here. For instance, given a charMsg that consist of 3 characters, 'a', 'b' and 'c', what should happen. A clear problem statement helps us to help you.

    0 讨论(0)
  • 2021-01-29 11:03

    Your hexOutput is a string, and I'm assuming charMsg is a character array. Suppose the first element in charMsg is 'p', or hex value 70. The documentation for Convert.ToChar(string) says it'll use just the first character of the string ('7'), but it's wrong. It'll throw this error. You can test this with a static example, like charMsg[n] = Convert.ToChar("70");. You'll get the same error.

    Are you trying to replace characters with hex values? If so, you might try using a StringBuilder object instead of your array assignments.

    0 讨论(0)
  • 2021-01-29 11:09

    Convert.ToChar(string) if it is empty string lead this error. instead use cchar()

    0 讨论(0)
提交回复
热议问题