1

I am trying to write a function to transform a string literal in Delphi/pascal to the C equivalent. A string literal in Delphi matches the regex ("#"([0-9]{1,5}|"$"[0-9a-fA-F]{1,6})|"'"([^']|'')*"'")+ so that the string

"This is a test with a tab\ta breakline\nand apostrophe '"

will be written in Pascal as

'This is a test with a tab'#9'a breakline'#$A'and apostrophe '''

I managed to strip the apostrophes, but I am having trouble managing the special characters.

4
  • 1
    Did you try writing a parser? Commented Feb 24, 2011 at 20:00
  • What exactly are you after? A "C" routine that does it? A "Delphi routine that does it? A regular expression? Commented Feb 24, 2011 at 20:02
  • @ignacio it is actually part of a larger parser, and I very much would like not to have to write another for the strings. @Cosmin I am looking for a C++ function that does it. Commented Feb 24, 2011 at 20:17
  • The delphi tag here is not helpful at all. Commented May 26, 2015 at 20:57

1 Answer 1

1

Simply use replaceApp() function that can be found at: http://www.cppreference.com/wiki/string/basic_string/replace

Then code can look as:

string s1 = "This is a test with a tab\\ta breakline\\nand apostrophe '";
string s2 = s1;
s2 = replaceAll(s2, "'", "''");
s2 = replaceAll(s2, "\\t", "'$7'");
s2 = replaceAll(s2, "\\n", "'$10'");
cout << "'" << s2 << "'";

Of course changes '\t' -> '$7' can be saved in some structure that you can use in loop instead of replacing each item in separate lines.

Edit:

Second solution (example taken from comment) with using map:

typedef map <string, string> MapType;
string s3 = "'This is a test with a tab'#9'a breakline'#$A'and apostrophe '''";
string s5 = s3;
MapType replace_map;
replace_map["'#9'"] = "\\t";
replace_map["'#$A'"] = "\\n";
replace_map["''"] = "'";
MapType::const_iterator end = replace_map.end();
for (MapType::const_iterator it = replace_map.begin(); it != end; ++it)
    s5 = replaceAll(s5, it->first, it->second);
cout << "s5 = '" << s5 << "'" << endl;
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, what I want to do is the opposite, in C I have "'This is a test with a tab'#9'a breakline'#$A'and apostrophe '''" and I want to obtain "This is a test with a tab\ta breakline\nand apostrophe '"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.