wizlog
wizlog

Reputation: 302

C# escape characters

e.g.

for (int i = 0; i < speaker.Length; i++) {
    s.WriteLine(speakerAmt[i] + \t + speakerID[i]);
}

I'm trying to get a tab character in-between speakerAmt[i] and speakerID[i]. Do escape characters need to be in " " " " (quotation marks)?

EDIT: Thank you! in less than 50 seconds, I had about 5 answers. I'm impressed!

Upvotes: 2

Views: 1845

Answers (9)

aloisdg
aloisdg

Reputation: 23511

since C#6, it is even better to do:

for (var i = 0; i < speaker.Length; i++)
{
    s.WriteLine($"{speakerAmt[i]}\t{speakerID[i]}");
}

It is Interpolated Strings

Upvotes: 1

Saber Amani
Saber Amani

Reputation: 6489

Do this :

for (int i = 0; i < speaker.Length; i++)
{
    s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);
}

And It's better to do following

for (int i = 0; i < speaker.Length; i++)
{
    s.WriteLine(string.Format("{0}\t{1}",speakerAmt[i],speakerID[i]);
}

Upvotes: 11

Jessica
Jessica

Reputation: 239

Yup!

for (int i = 0; i < speaker.Length; i++)
{
   s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);
}

Upvotes: 2

vcsjones
vcsjones

Reputation: 141588

Yes, the quotes are necessary.

s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);

Why it is necessary:

Because this is an escape sequence that is part of a string. \t is . Like:

var hi = "Hello\tWorld";

The compiler just interprets this in a special manner when used in the context of a string. The \ character in a string usually denotes the beginning of an escape sequence (exception: string literals). Here is another example that also uses a tab using a different way:

var hi = "Hello\u0009World";

You can read more about strings, literals, and escape sequences as part of the documentation.

Upvotes: 4

phoxis
phoxis

Reputation: 61910

escape characters are characters, therefore they needs to be in single quotes '\t'. Or you can construct a string with one escape character which makes it "\t" . Without any quotes \t is illegal.

Upvotes: 5

Rudu
Rudu

Reputation: 15892

Yes, they need to be in a string

for (int i = 0; i < speaker.Length; i++)
{
   s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);
}

Upvotes: 4

driis
driis

Reputation: 164281

Yes - you need to do this:

 s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);

Upvotes: 4

zellio
zellio

Reputation: 32484

Yes they do

string str = "Hello\tWorld!\n";

Upvotes: 4

Dylan Meador
Dylan Meador

Reputation: 2401

for (int i = 0; i < speaker.Length; i++)
{
    s.WriteLine(speakerAmt[i] + "\t" + speakerID[i]);
}

Upvotes: 4

Related Questions