Home >Backend Development >C++ >How to Efficiently Parse Command-Line Parameters into a String Array in C#?

How to Efficiently Parse Command-Line Parameters into a String Array in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-15 11:41:48772browse

How to Efficiently Parse Command-Line Parameters into a String Array in C#?

C# command line parameters are parsed into string arrays

In C#, it is often necessary to split a string containing command line parameters into a string array. This article explores standard functions and recommended methods to accomplish this task.

An important consideration is handling double-quoted strings containing spaces. Simply splitting a string based on whitespace is not enough, as it will incorrectly split double-quoted strings.

Standard functions

C# does not provide a standard function specifically for this purpose. This functionality can be achieved using a custom function that checks each character.

Recommended method

A recommended approach is to use the following code block:

<code class="language-csharp">public static IEnumerable<string> SplitCommandLine(string commandLine)
{
    bool inQuotes = false;

    return commandLine.Split(c =>
    {
        if (c == '\"')
            inQuotes = !inQuotes;

        return !inQuotes && c == ' ';
    })
    .Select(arg => arg.Trim().TrimMatchingQuotes('\"'))
    .Where(arg => !string.IsNullOrEmpty(arg));
}</code>

This method splits the string based on a function that checks for quotes and spaces, then trims the spaces and quotes.

Custom extension method

Another approach is to create a custom extension method:

<code class="language-csharp">public static IEnumerable<string> Split(this string str, Func<char, bool> controller)
{
    int nextPiece = 0;

    for (int c = 0; c < str.Length; c++)
    {
        if (controller(str[c]))
        {
            yield return str.Substring(nextPiece, c - nextPiece);
            nextPiece = c + 1;
        }
    }
    yield return str.Substring(nextPiece);
}

public static string TrimMatchingQuotes(this string input, char quote)
{
    if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote))
        return input.Substring(1, input.Length - 2);

    return input;
}</code>

Command line strings can be split using these methods:

<code class="language-csharp">string[] parameterArray = SplitCommandLine(parameterString).ToArray();</code>

Example usage

The following example demonstrates the use of the above method:

<code class="language-csharp">string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""[email protected]"" tasks:""SomeTask,Some Other Task"" -someParam foo";

string[] parameterArray = SplitCommandLine(parameterString).ToArray();

foreach (string parameter in parameterArray)
{
    Console.WriteLine(parameter);
}</code>

The above is the detailed content of How to Efficiently Parse Command-Line Parameters into a String Array in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn