Reputation: 69
Given a field/string like 'G,H,1,AA,T,AAA,1,E,A,H,....'. The characters can be in any combination/order. How do I search that string and return True when searching for just 'A' or 'AA'? i.e. If doing a search for say 'A', it should only find the 'A' between the E & H. Regards & TIA, Ian
Upvotes: 0
Views: 403
Reputation: 80097
Split this string into a list, for example with TStringList.CommaText
(alternatively, into an array with StrUtils.SplitString()
).
Then, just walk through the list and check every string (or use TStrings.IndexOf()
- note: it uses CaseSensitive
property, as Remy mentioned in comments).
If you are going to make many queries for the same list - sort it and use an effective binary search (TStringList.Find()
).
Upvotes: 2
Reputation: 8413
You can simply split your string into an array by your delimiter and search in that array, e.g.
function FindItem(const List, Item: string): Boolean;
var
SArr: TArray<string>;
S: string;
begin
Result := False;
//Separators could also be a parameter
SArr := List.Split([',']);
for S in SArr do
begin
//use S.Trim if needed
//use AnsiSameText(S, Item) for case insensitive check
if Item = S then
Exit(True);
end;
end;
If you need to search for multiple items in your data, you might want to sort the array and use a binary search.
TArray.Sort<string>(SArr);
Result := TArray.BinarySearch(SArr, Item, Tmp);
Another approach would be using regular expressions with word boundaries to search for whole words only
Result := TRegex.IsMatch(List, '\bA\b');
Upvotes: 2