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:
"programName car "is in blue building""
(programName is the name of the program, it is typed to execute the code and the arguments are sent after it like above) The message gets sent into args in the main method, but the "is in blue building" remains altogether in one argument. For the message I have shown, args[0] would contain "car", and args[1] would contain "is in blue building".
The main purpose to know this is because I am trying to replicate the interface and process in windows forms, I am unsure how I would solely get the string that I send in the quotation marks into one argument (as shown args[1]).
I have attempted this(let the variable "arg" be the string:
args = textBox1.Text;
if(textBox1.Text.Contains("\""))
{
int m = 0;
string quote = null;
string[] tmp = textBox1.Text.Split(' ');
for (int i = 0; i < tmp.Length; i )
{
if(tmp[i].Contains("\'"))
{
m ;
}
if (m == 1)
{
quote = tmp[i];
}
string quote1 = textBox1.Text.Replace(quote, "").Replace("\"", "");
string[] tmp1 = quote1.Split(' ');
quote = "'" quote "'";
tmp1 = quote.Split(' ');
}
however I am still working on it. but without any error, it will still be difficult to send it back to the main as it wants to be converted to args..
CodePudding user response:
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.