openlang

Escaping percent characters when calling String.Format?

My strings.xml file holds a SQL query, and I'm trying to construct the finished string in code with String.Format. The SELECT query contains a like clause along these lines:

SELECT ColumnA, ColumnB FROM records WHERE ColumnA LIKE '%pattern%'

For formatting, I substitute %1$s for 'pattern', giving me:

SELECT ColumnA, ColumnB FROM records WHERE ColumnA LIKE \'%%1$s%\'

Backslashes let me escape the single quotes. The % character, however, is something I haven't managed to escape.

What is the way to put a like clause into strings.xml?

The conversation continues 3

Follow the reasoning
  1. Permalink

    Adding to the solution already given, try this:

    query = query.replace("%", "%%");
  2. Permalink

    This regex replacement is more robust because it leaves existing doubled %% sequences in the input alone.

    query = query.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

Other sides of the same question

  1. NAK only when the message has a degree sign (serial, Emacs)

    Basically, Temp: 23C gets an ACK but Temp: 23°C gets a NAK, and the board shows nothing. The log line is rx: "\25". Lowering…

    Replies 1Latest activity emacs-lisp
  2. Formatting strings with F#

    I'm building an F# library for the first time Using string.Format gives me a complaint saying that the function doesn't exist…

    Replies 2Latest activity fsharp
  3. Truncating by bytes like the old C++, and Rust panics

    Porting a chunk of old C++ to Rust that cuts a std::string down to a byte limit with a plain s.substr(0, n), and I figured it…

    Replies 4Latest activity rustcpp