Sunday, August 18, 2013

C# - Escape Sequence Characters

There are few Escape Sequence that you can use when working with strings, this article will provide a great view of how can you use them to write a more efficient and clear code.

Escape Sequence = ES

ES 1 - “\b”:
This ES will delete the char from the left, for example:  

static void Main(string[] args)
        {
            string a = "123\b4";          
            Console.WriteLine(a);

            //Result = 124
        }
   
ES 2 - “\n”:
This ES will move all strings from his right to a new line, for example:  

static void Main(string[] args)
        {
            string a = "123\n4";          
              Console.WriteLine(a);

            //Result line 1 = 123
            //Result line 2 = 4     
        }

ES 3 - \”:
As you remember, the string variable start and closed with “”, if you want to add “” without manipulating the original string you can use this ES, for example:

 static void Main(string[] args)

        {
            string a = "123\"4";          
            Console.WriteLine(a);

            //Result  = 123"4         
        }

ES 4 - \”:
Same issue as ES 3, just with ‘ :

static void Main(string[] args)

        {
            string a = "123\’4";          
            Console.WriteLine(a);

            //Result  = 123'4         
        }

 ES 5 - \\:
This ES can be great when working with file system because you can add shared that start with “\\”.

static void Main(string[] args)

        {
            string a = "123\\4";          
            Console.WriteLine(a);

            //Result = 123\4         
        }

ES 6 - \t:
This ES will add ‘Tab’ for string

 static void Main(string[] args)

        {
            string a = "123\t4";          
            Console.WriteLine(a);
            //Result = 123 4         
        }
ES 7 - \r:

This ES will delete all strings located on his left side

 static void Main(string[] args)

        {
            string a = "123\r4";          
            Console.WriteLine(a);

            //Result = Beep Sound        
        }
ES 8 - \a:

I added this ES just for fun, if you use it you find your computer singing Beep…Beep….

static void Main(string[] args)

        {
            string a = "123\a4";          
            Console.WriteLine(a);

            //Result = Beep Sound        
        }

1 comment:

  1. Nice post!
    In the case of \r, I'd also mention the combination of \r\n, which has a different meaning: carriage return + line feed, Windows style for line breaks.

    ReplyDelete

My Presentations