Error cs1012 too many characters in character literal

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

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?

Community's user avatar

asked Apr 9, 2011 at 17:37

Jinx's user avatar

1

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 = "==";

answered Apr 9, 2011 at 17:40

Grant Thomas's user avatar

Grant ThomasGrant Thomas

44.1k10 gold badges85 silver badges127 bronze badges

0

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;
}

answered Apr 9, 2011 at 17:50

Only Bolivian Here's user avatar

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.

answered Apr 9, 2011 at 17:39

driis's user avatar

driisdriis

160k45 gold badges267 silver badges338 bronze badges

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 "&&": 

answered Apr 9, 2011 at 17:39

BrokenGlass's user avatar

BrokenGlassBrokenGlass

157k28 gold badges282 silver badges334 bronze badges

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("\.","")

answered Oct 6, 2020 at 14:28

sud's user avatar

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

answered Apr 9, 2011 at 17:53

Abe Miessler's user avatar

Abe MiesslerAbe Miessler

81.5k97 gold badges302 silver badges483 bronze badges

1

Sashaa_i

0 / 0 / 1

Регистрация: 02.11.2014

Сообщений: 64

1

27.12.2015, 12:11. Показов 23433. Ответов 3

Метки нет (Все метки)


return ‘pervy method’; — в этой строке выдает ошибку CS1012 Too many characters in character literal. Помогите пожалуйста разобраться что к чему и как исправить.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Zadtri
{
class Program
{
delegate string DelegateOne();
static void Main(string[] args)
{
    DelegateOne DL = delegate ()
 
    {
        return 'pervy method';
        };
    
    Console.WriteLine(DL());
    Console.ReadKey();
}
}
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

27.12.2015, 13:40

2

Лучший ответ Сообщение было отмечено Sashaa_i как решение

Решение

Sashaa_i, строки в C# должны быть в двойных кавычках. Одинарные кавычки используются для символов.



1



0 / 0 / 1

Регистрация: 02.11.2014

Сообщений: 64

27.12.2015, 13:58

 [ТС]

3

всё равно ошибки

Миниатюры

Ошибка CS1012 Too many characters in character literal.
 



0



0 / 0 / 1

Регистрация: 02.11.2014

Сообщений: 64

27.12.2015, 14:04

 [ТС]

4

а нет, все хорошо, получилось, спасибо)



0



  • Remove From My Forums
  • Question

  • User514441003 posted
    //I need to write Number of days in month of Year method . However, the error CS1012: Too many characters in character literal. I think error in ch==’10’ and ch==’12’ . But how to solve it . Besides this , what is «ildasm» how to use it? thx ——————————————————————————————
    using System; public class Hello { static void Main(string[] args) { int ch=Console.Read(); int state=0; switch (state) { case 0: if (ch ==’1′ || ch==’3′ || ch==’5′ || ch==’7′ || ch==’8′ || ch==’10’ || ch==’12’) { Console.WriteLine(«31»); } else if (ch ==
    ‘2’) goto case 2; else goto default; case 1: if (ch ==’4′ || ch==’6′ || ch==’9′ || ch==’11’) { Console.WriteLine(«30»); } else goto default; case 2: Console.WriteLine(«28 || 29!»); break; default: Console.WriteLine(«illegal character: » + (char) ch); break;
    } } }

I am trying to create a string in a javascript function to resolve path for an image handler url, but I am getting the following error:

Compiler Error Message: CS1012: Too many characters in character literal

The Javascript function code is given in the Code section. The following line is highlighted red as the error:

var ImageUrlPath = <%= sting.format(‘PicHandler.ashx?Src={0}&ImgId={1}&CallingSource={2}&maxHeight={3}&maxWidth={4}, «HWDetails»,’ + HImgID.ClientID + ‘, «EnlargedImage»,’ + 600 + ‘,’ + 600 + ‘;’ ) %>

Please help me fix error in this line.

function ChangeCursor()
    {
        this.className ='linkClassPointer';
       var control = document.getElementById('<% =HPost.ClientID %>').value;
        alert (control);
        
        if ((control==null) || (control=="") || (control.length==0))
             var x=1
        else
        {
            alert(control);
            var ImageRightPaneID=document.getElementById('<% =ImageRightPane.ClientID%>');
            var imgID = document.getElementById('<% =HImgID.ClientID %>').value;
            
            var ImageUrlPath = <%= sting.format('PicHandler.ashx?Src={0}&ImgId={1}&CallingSource={2}&maxHeight={3}&maxWidth={4}, "HWDetails",' + HImgID.ClientID + ', "EnlargedImage",' + 600 + ',' + 600 + ';' ) %>
            var imageSrc = <%= ResolveClientUrl(ImageRightPane.ImageUrl) %>; 
            
            
            ImageRightPaneID.onclick = "ImageRightPaneID.src='" + ImageSrc + "'";
 
           
            
                                   
            }
        
        return false;
    }

Open in new window

  • #1

Hello! I would like to know how to fix this error and what it means I am writing for the first time. And I’m new to C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public float speed;
    private Rigidbody rb;
    float MoveHorizontal;
    float MoveVertical;

    void Start()
    {
        rb = GetComponent<RigidBody>();
    }


    void FixedUpdate()
    {
        Vector3 movement = new Vector3(MoveHorizontal, 0.0f, MoveVertical);

        rb.AddForce(movement * speed);
    }

    public void Up()
    {
        MoveVertical = 1f;
    }

    public void Down()
    {
        MoveVertical = -1f;
    }

    public void StopMoveVertical()
    {
        MoveVertical = of;
    }

    public void Left()
    {
        MoveVertical = 1f;
    }

    public void Right()
    {
        MoveHorizontal = -1f;
    }

    public void StopMoveHorizontal()
    {
        MoveHorizontal = 'of';
    }
}

Skydiver


  • Skydiver

    Skydiver

  • Jul 1, 2022

In C#, strings are put between double quotes ("), not single quotes ('). The compiler is telling you that you are trying to put too many characters into a single character. There are special cases where you can use multiple characters to denote a single special characters. Ex. 't' for a Tab character.

Once you get past that problem, you’ll run into the problem of trying to assign a string to a float. C# is a strongly typed language. Variables (except dynamic variables) have a single specific type. You can only assign values of that type to that variable.

Skydiver


  • #2

In C#, strings are put between double quotes ("), not single quotes ('). The compiler is telling you that you are trying to put too many characters into a single character. There are special cases where you can use multiple characters to denote a single special characters. Ex. 't' for a Tab character.

Once you get past that problem, you’ll run into the problem of trying to assign a string to a float. C# is a strongly typed language. Variables (except dynamic variables) have a single specific type. You can only assign values of that type to that variable.

Last edited: Jul 1, 2022

у меня есть код JavaScript фотогалереи со слайдером, но есть проблема:

 var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";

    // check if the file is exiset -- it's running in bar() function -- run on servers and local host. 
    function UrlExists(url) {
        var http = new XMLHttpRequest();
        http.open('GET', url, false);
        http.send();
        return http.status != 404;
    }

    // push images paths to array 
    function bar() {
        var exict = 0;
        var counter = 0; //counter of array's index
        for (var i = 1 ; exict < 30; i++) {
            // if there isn't .jpg or .gif
            if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
                exict = exict + 1;
            }
            // if there is .jpg
            if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
                arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
                counter = counter + 1;
            }
            // if there is .gif 
            if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
                arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
                gifIndex.push(i);
                counter = counter + 1;
            }
        }
}

но это не сработало, поэтому я попытался изменить var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;

но я получил ошибку: «ошибка CS1012: слишком много символов в символьном литерале». Я до сих пор не уверен, что это проблема, так как мой исходный код работает (вы можете увидеть начальное изображение продукта, загруженное при посещении сайта). .баумхаус и нажмите на ассортимент продуктов, а затем на любой продукт, вы увидите действие — до того, как оно исчезнет, ​​как только оно попытается отобразить миниатюры).

  • Our
  • Forum
  • Using Umbraco And Getting Started

Press Ctrl / CMD + C to copy this to your clipboard.

Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Sonja

    133 posts

    621 karma points

    Oct 08, 2018 @ 07:01

    Sonja

    Hi

    I’m trying to use UmbClientMgr.openModalWindow and I’m having problem:

    <button class="stackedContent default" href="@item.Url" title="@item.Title" id="TestBtn" onclick="@UmbClientMgr.openModalWindow('mypage.aspx', 'some title', true, 800, 600);">
    

    I’m getting Compiler Error Message: CS1012: Too many characters in character literal

    please advise

  • Chriztian Steinmeier

    Hi Sonja,

    This is a C# syntax thing that gets me a lot too — it’s because in C# the single quote character is used to denote a single character. So you need to change the <button> tag and use double quotes instead (yes, even though you’re already inside a pair of double quotes) — e.g.:

    <button class="stackedContent default" href="@item.Url" title="@item.Title" id="TestBtn" onclick="@UmbClientMgr.openModalWindow("mypage.aspx", "some title", true, 800, 600);">
    

    Hope that helps,

    /Chriztian

  • Sonja

    133 posts

    621 karma points

    Oct 08, 2018 @ 07:17

    Sonja

    Thanks Chriztian this solved this problem. For the new problems I’ll go in new thread

Понравилась статья? Поделить с друзьями:
  • Error cs1010 newline in constant
  • Error cs1009 нераспознанная escape последовательность
  • Error cs1003 синтаксическая ошибка требуется
  • Error cs1003 syntax error expected unity
  • Error cs1002 требуется