randomUser1212421
randomUser1212421

Reputation: 15

How would I make a variable of type args take a quote or string as an argument among others?

When I run my code through the CMD, the message gets sent into:

void Main(string[]args) 

As everybody does if they use C# on visual studio. But when you run your code from CMD and type a message. it appears the argument can take in a message such as:

Upvotes: 1

Views: 366

Answers (1)

SteveOhByte
SteveOhByte

Reputation: 96

You can treat quoted text as one string without using the Split function, instead making use of Regex. Take the following snippet as an example:

// In your case just read from the textBox for input
string input = "cars \"testing string\"";

// This code will split the input string along spaces,
// while keeping quoted strings together
string[] tmp = Regex.Split(input, 
    "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

// Now must remove the quotes from the Regex'd string
string[] args = tmp.Select(str => str.Replace("\"", "")).ToArray();

// Now when printing the arguments, they are correctly split
for (int i = 0; i < args.Length; i++)
{
    Console.WriteLine("args[" + i + "]:'" + args[i] + "'");
}

I found the particular regex string you needed at this link, here on stack overflow.

Upvotes: 3

Related Questions