Home > Software design >  c# split string by underscore
c# split string by underscore

Time:07-28

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.

CodePudding user response:

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

CodePudding user response:

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 .IndexOfLast() to find the index of the last underscore in the string, and then use .Substring() to get rid of it.

String.IndexOfLast()

String.SubString()

  • Related