2

When I try to format a string such as '%s%s' using a line of code like so:

format('%s%s', [x]);

I get an exception because you can't have multiple '%s' without using an array with the same amount of arguments such as:

format('%s%s', [x,x]);

However, I don't know how many '%s' I will have to format and therefore I don't know how long the array would have to be. I also only want '%s' assigned to only 1 value.

Is there a way in which you can use multiple '%s' and assign them all to the same index?

4
  • 1
    Your question is unclear. Can you provide some sample code that demonstrates the problem (including some sample calls with actual values)? Delphi's Format function clearly expects you to pass a value for each specifier you provide to it. What does assign them all to the same argument mean? If you want to pass %s%s as the specifier with only one value 'abc', then why do you need format at all? Commented Apr 20, 2018 at 20:51
  • 5
    You can use an index. Something like %0:s to get the first argument. Commented Apr 20, 2018 at 20:52
  • 1
    This is covered in the Delphi documentation See the format specifiers at the end, specifically the part above NOTE: Commented Apr 20, 2018 at 21:00
  • Thank you, I solved the problem after reading the documentation. Commented Apr 20, 2018 at 21:09

2 Answers 2

8

As described in the documentation you can use an index specifier to identify the argument by a zero based index. The index specifier is written immediately after the % and is followed by a :.

Your example would be:

Format('%0:s%0:s', [x])
Sign up to request clarification or add additional context in comments.

1 Comment

the guy say he don't know how many %s he will have to format so we can assume he don't know also the format string and can't update it ;)
-2
MyStr := StringReplace('%s%s', '%s', x, [rfreplaceALL]);

2 Comments

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.
@loki code only answers are really not to be recommended. They are perhaps acceptable when they clearly answer the question in a way that leaves no room for doubt. This code does not answer the question that was asked. Even worse, the code does not compile.

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.