• Status: Solved
• Priority: Medium
• Security: Public
• Views: 356

Find value in comma separated string

Hi,

I need to determine if StringA contains an exact match for StringB.
Please be aware that the value of StringB must be matched with a value in StringA based on the whole value between the comma's.

Example 1:
StringA = '0,4,5,10';
StringB = '1';
NO MATCH as value '1' can't be found in StringA (as '10' is not an exact match).

Example 2:
StringA = '0,1,4,5,10';
StringB = '1';
EXACT MATCH as value '1' can be found in StringA.
0
Stef Merlijn
1 Solution

Commented:
Use Filter of dataset like the follwoing

Table1.Filtered := False;
Table1.Filter := 'MyField LIKE '+QuotedStr('%,1,%')+'or MyField LIKE '+
QuotedStr('1,%')+'or MyField LIKE '+QuotedStr('%,1');
Table1.Filtered := True;
0

Commented:
Or if you want to find text use the this function

function FindMyStr(StringB: string): boolean;
begin
Result := (Pos(',1,', StringB) > 0) or (Pos('1,', StringB) = 1)
or (Pos(',1', StringB) = Length(StringB) - 1);
end;
0

Commented:

You could use stringlists

eg

function StrContains(const ASource, ACompare: string; out value: string): Boolean;
var
S1, S2: TStringList;
I: Integer;
begin
Result := False;
S1 := TStringList.Create;
S2 := TStringList.Create;
try
S1.Delimiter := ',';
S2.Delimiter := ',';
S1.StrictDelimiter := True;
S2.StrictDelimiter := True;

S1.DelimitedText := ASource;
S2.DelimitedText := Acompare;
for I := 0 to S1.Count -1 do
begin
Result := S2.IndexOf(S1[I]) > 0;
if Result then
begin
Value := s1[I];
Break;
end;
end;
finally
S1.Free;
S2.Free;
end;
end;
0

DeveloperAuthor Commented:
Perfect thank you.
0

Oracle dbaCommented:
if you want to do this on a database using parameters
like so:

oracle:
select instr(','||:hay||',',','||:needle||',') needle_in_hay from dual;
sample:
:hay = '1,2,3,4,5'
:needle = '4'

returns the position of the needle in the hay or 0 if it's not found

qry.Sql.text := 'select instr('',''||:hay||'','','',''||:needle||'','') needle_in_hay from dual';
qry.parambyName('hay').AsString := '1,2,3,4,5,6';
qry.paramByName('needle').AsString := '5';
qry.Open;
if qry.FieldByName('needle_in_hay').AsInteger > 0 then
ShowMessage('Needle is in hay ');
0

Oracle dbaCommented:
ah ... didn't refresh after going to lunch :)
0

Commented:
Is it my method false?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.