0

I am having issues detecting double quotes ("") or quotation marks in general from a string.

I tried using the str.find(""") or str.find("""") however, the first one doesn't compile and the second does not find the location. It returns 0. I have to read a string from a file, for example:

testFile.txt

This is the test "string" written in the file.

I would read the string using and search it

string str;
size_t x;
getline(inFile, str);
x = str.find("""");

however the value returned is 0. Is there another way to find the quotation marks that enclose 'string'?

Useless
  • 64,155
  • 6
  • 88
  • 132
JoshuaZz
  • 15
  • 1
  • 4
  • Use backslash on the second quote. Otherwise the second quote just terminates the string. ie "a""b" is the same as "a" "b" which is the same as "ab". So """"" is the same as "" or a null string – doug Apr 04 '20 at 21:46
  • You have to escape the double quote in your find string. Try str.fine("\""). – Buddhima Gamlath Apr 04 '20 at 21:48

3 Answers3

5

The string """" doesn't contain any quotes. It is actually an empty string: when two string literals are next to each other, they get merged into just one string literal. For example "hello " "world" is equivalent to "hello world".

To embed quotes into a string you can do one of the following:

  • Escape the quotes you want to have inside your string, e.g. "\"\"".
  • Use a raw character string, e.g. R"("")".
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

You should use backslash to protect your quotes.

string a = str.find("\"")

will find ".

minmon
  • 18
  • 5
0

The " character is a special one, used to mark the beginning and end of a string literal.

String literals have the unusual property that consecutive ones are concatenated in translation phase 6, so for example the sequence "Hello" "World" is identical to "HelloWorld". This also means that """" is identical to "" "" is identical to "" - it's just a long way to write the empty string.

The documentation on string literals does say they can contain both unescaped and escaped characters. An escape is a special character that suppresses the special meaning of the next character. For example

\"

means "really just a double quote, not with the special meaning that it begins or ends a string literal".

So, you can write

"\""

for a string consisting of a single double quote.

You can also use a character literal since you only want one character anyway, with the 4th overload of std::string::find.

Useless
  • 64,155
  • 6
  • 88
  • 132