-1

I want to make a if where it checks if a Substring is a ". Like here:

char comma = '"'
if(String.Substring(6, 1) == comma)

But this doesnt doesn't work and it gives me this error

Error CS0019 The == operator cannot be used on operands of the type "string" and "char".

Is there an alternative to the char version? String doesnt work either, because the second quotation is ending the first and the 3rd is without end.

  • 1
    That's not a comma, by the way – Caius Jard Jul 16 '21 at 16:39
  • foo.SubString(6, 1)[0] == comma or the much more logical foo[6] == comma. *Do* post the actual code you wrote, this wasn't it. – Hans Passant Jul 16 '21 at 16:40
  • 2
    By "String doesnt work either, because the second quotation is ending the first and the 3rd is without end." I assume you mean "I don't know how to write a string literal containing a double-quote" - it's `"\""` – Jon Skeet Jul 16 '21 at 16:44

1 Answers1

3

If you want to check whether a particular char is at a particular place in a string, treat the string like an array with an index:

char quote = '"'
if(someString[6] == quote)

Indexing a string returns the char at that place

If you want substrings there is also a new syntax for that:

someString[6..8] //starting at index 6, ending at 8, length of 2

Prefixing the number with ^ means "from the end of the string

someString[^6..^4] //starting at index 6 from the end, ending at 4 from end, length of 2

You can mix and match start and end so long as start position is before end position. This string must be at least 10 length:

someString[6..^4] //starting at index 6, ending at 4 from end, length of (length-10)

You can omit the start and it is assumed that you meant 0

You can omit the end and it is assumed you meant ^0

These ranges return strings, not chars

Caius Jard
  • 72,509
  • 5
  • 49
  • 80