delphistring-comparisonparamstr

How to read value of ParamStr with different deliminators?


When you read ParamStr(), it's deliminated by spaces between each parameter. However, I've seen many command-line arguments which accept a space between the parameter name and its paired value, while also accepting an equals = sign and even no deliminator (just prefixed with the param name) or no value.

Here's some examples of possible param strings:

-name value
/name value
-name=value
/name=value
-namevalue
/namevalue
-name -nextname
/name /nextname
-name="value with spaces"
/name="value with spaces"

...etc.

What I would like to do is two things both related... Check if a parameter name exists, and read the value of the parameter. For example...

if ParamExists('ParamName') then
  SomeString:= ParamValue('ParamName')
else
  SomeString:= 'SomeOtherString';

Is there something in Delphi which can do this? If not, how do I do this? Everything I find when searching for this just leads me to the same basic example:

for i := 0 to ParamCount do
  ShowMessage(ParamStr(i));

It also needs to be case sensitive. I'm looking for something in particular like OSQL and similar command-line tools use where '-s' could be different from '-S'.

The problem is that if I use a space as a deliminator, I have no clue how to recognize when it's part of the previous parameter, because it splits them by spaces. How do I get around this?

I'm sure there's a standard term for this too, it's the common formatting of command-line arguments. But I don't know how to read them properly using just ParamStr. It seems ParamStr falls short of what it's usually used for.

To be clear, I don't necessarily need to support every above example - those are just examples I've seen before.


Solution

  • ParamStr() (and consequently FindCmdLineSwitch()) is not flexible enough to handle all of the examples you have shown. You will have to call the Win32 API GetCommandLine() function and parse it manually.