"Too many characters in character literal error"

C#Char

C# Problem Overview


I'm struggling with a piece of code and getting the error:

> Too many characters in character literal error

Using C# and switch statement to iterate through a string buffer and reading tokens, but getting the error in this line:

>case '&&': > >case '||': > >case '==':

How can I keep the == and && as a char?

C# Solutions


Solution 1 - C#

This is because, in C#, single quotes ('') denote (or encapsulate) a single character, whereas double quotes ("") are used for a string of characters. For example:

var myChar = '=';

var myString = "==";

Solution 2 - C#

Here's an example:

char myChar = '|';
string myString = "||";

Chars are delimited by single quotes, and strings by double quotes.

The good news is C# switch statements work with strings!

switch (mytoken)
{
    case "==":
        //Something here.
        break;
    default:
        //Handle when no token is found.
        break;
}

Solution 3 - C#

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

Solution 4 - C#

A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes:

case "&&": 

Solution 5 - C#

I believe you can do this using a Unicode encoding, but I doubt this is what you really want.

The == is the unicode value 2A76 so I belive you can do this:

char c = '\u2A76';

I can't test this at the moment but I'd be interested to know if that works for you.

You will need to dig around for the others. Here is a unicode table if you want to look:

http://www.tamasoft.co.jp/en/general-info/unicode.html

Solution 6 - C#

I faced the same issue. String.Replace('\\.','') is not valid statement and throws the same error. Thanks to C# we can use double quotes instead of single quotes and following works String.Replace("\\.","")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJinxView Question on Stackoverflow
Solution 1 - C#Grant ThomasView Answer on Stackoverflow
Solution 2 - C#Only Bolivian HereView Answer on Stackoverflow
Solution 3 - C#driisView Answer on Stackoverflow
Solution 4 - C#BrokenGlassView Answer on Stackoverflow
Solution 5 - C#Abe MiesslerView Answer on Stackoverflow
Solution 6 - C#sudView Answer on Stackoverflow