-3

I have list of items:

Apple\3
Orange\8
Kivi\9

I wish to add these items in C # array:

string[] fruit={"Apple\3","Orange\8","Kivi\9"};

But it return me error as the backslash not acceptable ("\"), by the way the backslash is a must to include, anyone have ideas?

Shi Jie Tio
  • 2,479
  • 5
  • 24
  • 41
  • 1
    You need to either escape your backslash `"Apple\\3"` or use verbatim strings `@"Apple\3"`. Look up escape characters if you want to know why. – Loocid Nov 25 '19 at 02:37

3 Answers3

2

Backslash is normally being interpreted by C# as there is going to be a command following... such as \n for linebreaking.

If you need the backslash in your string, you simply have to add another backslash.

Apple\\3
Orange\\8
Kivi\\9
pensum
  • 980
  • 1
  • 11
  • 25
0

\ signals the beginning of an escape sequence, which tells it to not read what immediately follows it in a string literally.

so if you wanted to include the character " in a string, you can use \" to let it know that you are not ending the string. if you wanted to include \ in a string you use \\ . there are also sequences that you can use to do something, like to change text color in terminal. https://en.wikipedia.org/wiki/Escape_sequence

also fun fact, you can use \ in discord also, if you are trying to write some math like 5 * 6 * 7, it would normally interpret the * 6 * to mean that it should be in bold. instead, you can write 5 \* 6 \* 7 and it will display properly! also apparently this is true for stackoverflow as well haha

awaymsg
  • 31
  • 7
0

The backslash \ is escape charter and cannot be interpreted and treated as special character. This can be fixed by adding one more backslash after escape character \\ like this

string[] fruit= {"Apple\\3","Orange\\8","Kivi\\9"};

or adding @ before string like this

string[] fruit= {@"Apple\3",@"Orange\8",@"Kivi\9"};
Saif
  • 2,611
  • 3
  • 17
  • 37