Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing a Char with equivalent string

I have the following class as a DataSource for a ListBox:

class SeparatorChars
{
    /// <summary>
    /// Text to describe character
    /// </summary>
    public string Text { get; set; }

    /// <summary>
    /// Char value of the character
    /// </summary>
    public char Value { get; set; }

    /// <summary>
    /// Represent object as string
    /// </summary>
    /// <returns>String representing object</returns>
    public override string ToString()
    {
        return Text + " '" + Value + "'";
    }
}

The problem is, this by default will use the Value just as a regular character added to a string, for example if I define this class for Tab like this:

var TabSeparator = new SeparatorChars {Text = "Tab", Value = '\t'}

The string representation will be:

Tab '     '

But I need it to be

Tab '\t'

How to do this?!

like image 758
Saeid Yazdani Avatar asked Jan 03 '12 11:01

Saeid Yazdani


People also ask

How do I convert a char to a string?

We can convert a char to a string object in java by using the Character. toString() method.

How do you find the ASCII equivalent?

If you have the ASCII code for a number you can either subtract 30h or mask off the upper four bits and you will be left with the number itself. Likewise you can generate the ASCII code from the number by adding 30h or by ORing with 30h.

How do you compare ASCII values between two strings?

The Java comparison method calculates the difference of ASCII values for each character of two strings passed. If the difference comes to “0”, the strings are exactly equal. Otherwise, it prints the difference of ASCII value for the first non-matched character. If the value is negative, the first string is greater.


2 Answers

Admittedly ripped mostly from this post and untested.

public override string ToString()
{
    return ToLiteral(Text + " '" + Value + "'");
}

private string ToLiteral(string input)
{
    var writer = new StringWriter();
    CSharpCodeProvider provider = new CSharpCodeProvider();
    provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
    return writer.ToString();
}
like image 129
Jason Down Avatar answered Sep 28 '22 07:09

Jason Down


Here's a blog post with some sample code: Mark Gu: Escape Sequences in C#

like image 41
Henk Holterman Avatar answered Sep 28 '22 06:09

Henk Holterman