I have a simple array of strings example given below returning from an API, which we do not have a much control.
I am searching for "ABC HG". This is incomplete string as it should be either ABC HGL or any other characters after "HG" if you see in the array example. This is an API, which gives me all results even it is a partial string. However, this string example search should be considered as incomplete string, and should not give me any result. How do I do this through linq or elegant way?
string[] strings = {"This is not ABC HGL",
"I am going to ABC HGL",
"What is ABC HGT",
"Excellent ABC HGU"}
I simply need to find for a search string, if it is an incomplete string and do not result anything.
CodePudding user response:
I do not think Linq would be appropriate for this. The approach i would take is to check if the search string exist, and then check if the characters to the left and right of the search target are white spaces. So something like this:
public bool IsMatch(string stringToCheck, string searchString);
int index = 0;
while( index < stringToCheck.Length){
index = stringToCheck.IndexOf(searchString, index);
if(index < 0) return false;
var indexBefore = index - 1;
var indexAfter = index searchString.Length ;
var hasWhitespaceBefore = indexBefore < 0 || !char.IsLetter(stringToCheck[indexBefore];
var hasWhitespaceAfter = indexAfter >= stringToCheck.Length || !char.IsLetter(stringToCheck[indexBefore];
if( hasWhitespaceBefore && hasWhitespaceAfter) return true;
index ;
}
Note that code is untested. Be aware of of-by-one errors!
CodePudding user response:
You can use regular expressions to do this
var inputStrings = new string[]
{
"asdfasdf ABD DGT world",
"asdfasdf ABD DGL world",
"asdfasdf ABD DG world",
"asdfasdf ABD DG",
"asdfasdf ABD DGL",
"asdfasdf ABD DGT"
};
var searchText = "ABD DG";
var regex = new Regex($@"{searchText}(?!\S)");
var matchingStrings = inputStrings.Where(x => regex.IsMatch(x));
// Returns "asdfasdf ABD DG world" and "asdfasdf ABD DG"