c# split string by underscore

Viewed 53

I am working on some string generator task. I have some sample string duplicate_config_dev_V2 and I want to get output duplicate_config_dev. If input is duplicate_config_dev_V3 then I want to get duplicate_config_dev. I tried as below.

int countUnderScore = input.Count(c => c == '_');
if(countUnderScore > 0 )
{
    input = input.Split('_')[countUnderScore-1];
}

This code returns Dev as output but I want to return duplicate_config_dev.

3 Answers

You can solve this problem using String.Split() like you have started, but that means you will have to re-assembly the parts of the string.

Instead I would use .LastIndexOf() to find the index of the last underscore in the string, and then use .Substring() to get rid of it.

String.LastIndexOf()

String.SubString()

If you want to remove the part after the last underscore, you can use the LastIndexOf method:

var input = "duplicate_config_dev_V2";
var index = input.LastIndexOf("_");
if (index >= 0)
  Console.WriteLine(input.Substring(0, index));

Output of above sample:

duplicate_config_dev

I'd very much consider using Regex here. It seems important that the string ends with _V# (# is some number).

This works:

var input = "duplicate_config_dev_V2";
var regex = new Regex(@"^(.*)_V\d+$");
var match = regex.Match(input);
if (match.Success)
    Console.WriteLine(match.Groups[1].Value);
Related