Finding out if a delimited string contains a specific value the easy way

One of the things I do on a regular basis is to read somebody else's code in order to learn from it. And just this week I was reading some code of which I at first did not understand what was happening and then it struck me:

var searchString = " " + inputString + " ";
if(searchString.Contains(" " + searchValue + " ")){
  // do something
}

The inputString here contains a space(" ") delimited list of values. What I used to do to find out if a delimited string contains a specific value is to call string.Split("<separator>") to create an array and then use Linq or a loop to iterate through the array and verify if this array contains the value. This is however very inefficient. Just prepending en postpending the string value with the separator and then call string.Contains("<separator>" + searchValue + "<separator>") works perfectly fine and is much more optimized.

Prepending and postpending is required to prevent you from finding false positives. Imagine an inputString like this: "12 126 123" while searching for a value of "26".

3 Comments

Comments have been disabled for this content.