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

How to Split a Command-Line String into a String Array in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-15 12:02:43495browse

How to Split a Command-Line String into a String Array in C#?

C# command line parameter string is split into string array

This article aims to solve the problem of splitting a single string containing command line parameters into an array of strings, as C# does when specifying these parameters on the command line.

Why do you need a custom function?

Unfortunately, C# has no built-in function to split strings based on specific character conditions. This is ideal for this task since we want to split based on whitespace, taking into account quoted strings.

Regular expression scheme

Someone might suggest using regular expressions (regex) to achieve this. However, regular expressions can be complex and difficult to maintain, especially when it comes to correctly handling quoted strings.

Custom segmentation function

To overcome this limitation, we will create our own custom Split function:

<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);
}</code>

This function takes a predicate as argument to determine whether the character should split the string.

Quotation mark processing

To handle quoted strings, we define a TrimMatchingQuotes extension method:

<code class="language-csharp">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>

This method only removes matching quotes that appear at the beginning and end of the string.

Use in combination

Combining these techniques, we can create a function to split command line strings:

<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 function splits a string based on spaces, ignoring spaces in quoted strings. It then trims each argument, removing surrounding quotes if present.

Example usage

To use this function:

<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();</code>

parameterArray will contain the expected array of string parameters corresponding to the command line string.

The above is the detailed content of How to Split a Command-Line String 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