0
votes

Net core. 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. Can someone help me withi this. Any help would be appreciated. Thank you.

2

2 Answers

1
votes

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));

Above sample outputs

duplicate_config_dev
0
votes

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()