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.

Meldin A.
  • 43
  • 1
  • 4

3 Answers3

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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();
L.B
  • 114,136
  • 19
  • 178
  • 224
-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

  • `@"[^\\s\"']+|\"([^\"]*)\"";` is not a compilable string.. if you mean `"[^\\s\"']+|\"([^\"]*)\""` it doesn't do the work... – L.B Jul 01 '14 at 13:46