-4

is there way to find out the indexof backslash in string variable?

i have string

var str = "      \"AAP, FB, VOD, ART, BAG, CAT, DDL\"\n    "

int stIdx = str.indexof('\"') // output as 6

int edIdx = str.indexof('\', stIdx+1); // output as -1

output i'm looking for is as below

AAP, FB, VOD, ART, BAG, CAT, DDL
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • I would suggest that you have to escape the character i.e. you have to use `'\\'` (double backslash) in this particular case – Jaood_xD Sep 01 '22 at 13:23
  • 1
    I think your string represents a `UTF-16` string. In that case the `\n` represents a single character for a new line. Thus searching for the character \ won't be able to find it as that is a different character than a new line. – NotFound Sep 01 '22 at 13:26
  • Does this answer your question? [How do I write a backslash (\‌) in a string?](https://stackoverflow.com/questions/18532691/how-do-i-write-a-backslash-in-a-string) – Charlieface Sep 01 '22 at 13:27
  • ```\n``` in your string gets replaced as a single newline character and therefor there is no ```\``` character in the string. – phuzi Sep 01 '22 at 13:28
  • 2
    Note that the code you've written doesn't have any output, as it doesn't compile, for multiple reasons. This is why it's always important to provide a [mcve] rather than pseudo-code. – Jon Skeet Sep 01 '22 at 13:30

3 Answers3

1

You need to escape your backslash to use it as a char value.

Cause backslash is a special character, '\' didn't refer to backslash as a character, but as an instruction which let you escape any character.

int index = str.IndexOf('\\'); //should give you the right answer

Natlink
  • 21
  • 3
0

The character sequence '\n' is used for a newline.

string str = "Hi\n";

In the above example str consists of the characters 'H', 'i', and a newline character. There is no '\' character.

Try the following:

int edIdx = str.indexof('\n', stIdx+1);
Jonathan Dodds
  • 2,654
  • 1
  • 10
  • 14
0

A \" in a string is not a backslash followed by a quote, but just a quote. The backslash in the string literal escapes the quote: it should be just a character, not the end of the string constant.
The \n is not an escaped 'n' (it wouldn't need escaping) but a (single) newline character.

Your string literal doesn't really contain any backslashes.

Your code, with typos fixed:

var str = "      \"AAP, FB, VOD, ART, BAG, CAT, DDL\"\n    ";

int stIdx = str.IndexOf('"')+1; // output as 7 - you don't want position of " but 'A'

int edIdx = str.IndexOf('"', stIdx); // output as 39

Console.WriteLine($"from {stIdx} to {edIdx}"); // "from 7 to 39"
Console.WriteLine(str.Substring(stIdx, edIdx-stIdx)); // "AAP, FB, VOD, ART, BAG, CAT, DDL"

In a character literal (delimited by single quotes), you do not need to escape the double quote, so '"' works fine. Although it is no problem if you do escape it: '\"' - which is still a single " character.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111