1

I have below string

string arguments = "-p=C:\Users\mplususer\Documents\SharpDevelop Projects\o9\o9\bin\Debug\o9.exe""-t=False""-r=TestRun";

I want to split string with "-t=" and get false value

if (arguments.Contains("-t="))
{
    string[] value = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None);
    if (value.Length != 0)
    {
        mode = value[1].Replace("\"", "");
    }
}
2
  • 2
    String.Split never returns an empty string[]. If the delimiter is not contained you get an array with one string which is the complete source string. So your value.Length != 0-check is incorrect. It's redundant anyway because you have used already if (arguments.Contains("-t=")). Commented Oct 27, 2017 at 10:51
  • Your code for setting arguments wouldnt compile .. so maybe something else is wrong Commented Oct 27, 2017 at 10:52

3 Answers 3

2

Simply make an IndexOf:

var i = myString.IndexOf("-t=") + 3;
if(i != -1)
    value = myString.SubString(i, myString.IndexOf("\"", i) - i);

You can also use a regex for this:

var r = new Regex("-t (true|false)");
var g = r.Match(myString).Groups;
if(g.Count > 1)
    value = Convert.ToBoolean(g[1].ToString());
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it also like this like your approach without regex:

string arguments = "-p=C:\\Users\\mplususer\\Documents\\SharpDevelop Projects\\o9\\o9\\bin\\Debug\\o9.exe\" \"-t=False\" \"-r=TestRun";

if (arguments.Contains("-t="))
{
    string splitted = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None)[1];
    string value = splitted.Split(new string[] { "\"" }, StringSplitOptions.None)[0];
} 

Comments

0

When you split on "-t", you get two fragments. The fragment after that delimiter also contains a "-r" option - which is the issue you are probably seeing.

If you know that the "-t" option is always followed by a "-r", you could simply split on new string[] { "\"-t=", "\"-r=" }. Then you get three fragments and you still want the second one (at index 1).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.