2

I have a set of enum values and an input string, and in case the string has a suffix which is one of the enum names, I want to delete it.

For example, let's say I have

enum colors { red, blue, green, white }

And I receive the input string "str = evergreen", I want to do something like

if (str.endsWith(colors)) {
   output = str.trimSuffix(colors)
}

and get the string ever in output. Modifying str itself instead of saving it to a new variable is also fine.

is there a simple and/or elegant way to do it without hard coding the enum as array of strings and iterate over it?

MaayanA
  • 27
  • 2
  • You can use `Enum.GetValues(typeof(colors))` to avoid having to hard code them. – C.Evenhuis Jun 08 '20 at 12:01
  • ```Enum.GetValues(typeof(colors))``` just should just get the appropriate integer values, you should use ```Enum.GetNames(typeof(colors))``` instead – TinoZ Jun 08 '20 at 12:03
  • where is trimSuffix defined? – Bernard Vander Beken Jun 08 '20 at 12:06
  • Thanks! Then now I only need to understand how to remove the suffix if it's an array element, I think that finding this solution might be simpler – MaayanA Jun 08 '20 at 12:07
  • 1
    @BernardVanderBeken, it's not, its a kind of pseudo-code. I'm trying to find something that has the functionality of trimSuffix - take str and trim its suffix if the suffix is one of the names in colors – MaayanA Jun 08 '20 at 12:09

1 Answers1

2

This code will remove any suffix from str that is defined in the enum below

var values = Enum.GetNames(typeof(colors));
var str = "evergreen";

var suffix = values.OrderByDescending(v => v.Length)
    .FirstOrDefault(v => str.EndsWith(v));

if(suffix != null)
{
    str = str.Substring(0, str.Length - suffix.Length);
}

enum colors { 
   red,
   blue,
   green,
   white 
}
mortb
  • 9,361
  • 3
  • 26
  • 44