String must be exactly one character long

前端 未结 4 626
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题