2

I want to split a string into parts, to retrieve arguments.

I already made that function:

static private string getparam(string input, int index)
    {
        string[] arrparams = input.Split(' ');

        if (arrparams.Length <= index) return "";

        return arrparams[index];
    }

But when i pass an argument like:

upload C:\Visual Studio

it will see "C:\Visual" as the first argument and "Studio" as the second and split em.

Now i thought about making something like an exception in the Split-Function: When the argument is given between quotes, it should ignore the spaces in it.

Then, when i pass the arg like this: upload "C:\Visual Studio", the first argument should be C:\Visual Studio

So how could i implement this?

Thank you.

2

3 Answers 3

10

The reason for the current behaviour is because you are splitting on space, so it shouldn't be a shock to find that it splits on space.

But the simpler fix is: don't do this. Let the runtime worry about it:

static void Main(string[] args) { ... }

and job done; all ready-parsed into separate tokens obeying the expected rules.

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you can use ``` Environment.GetCommandLineArgs() ```
I want to give commands from an online website. And my app is no command line app.
4

"I want to give commands from an online website. And my app is no command line app"

You can use Regex.

string[] arrparams = Regex.Matches(input, @"\""(?<token>.+?)\""|(?<token>[^\s]+)")
                    .Cast<Match>()
                    .Select(m => m.Groups["token"].Value)
                    .ToArray();

1 Comment

Wow! This one works. Thank you mate!
-1

You can do this with a regex.split method.

You code should be modified as

using System;
using System.Text.RegularExpressions;
static private string getparam(string input, int index)
{
   <b>string pattern = @"[^\\s\"']+|\"([^\"]*)\"";
   string[] arrparams = Regex.Split(input,pattern);</b>
   if (arrparams.Length <= index) return "";
   return arrparams[index];
}

This bold code with match and split a space and when it is double quotes it will take as such. Post back if you find any issues.

Thanks Arun

1 Comment

@"[^\\s\"']+|\"([^\"]*)\""; is not a compilable string.. if you mean "[^\\s\"']+|\"([^\"]*)\"" it doesn't do the work...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.