检查字符串是否包含子字符串,但最后不是

use*_*186 0 delphi

有没有在delphi内置函数来查找字符串是否包含子,但不是在结束了吗?

例如,假设我有这些字符串:

G15001,
G15005,
G15015,
G14015,
G14004,
PLU15010,
PLU14015

我想在字符串为G15001 G15005,G15015,PLU15010和搜索的子字符串为15时返回true,但在G14015或PLU14015时返回false,因为它们最后只有15.

Dav*_*nan 5

使用Pos检查,如果子都可以找到.然后检查子串是否位于末尾.

function ContainsBeforeEnd(const str, substr: string): Boolean;
var
  P: Integer;
begin
  P := Pos(substr, str);
  if P = 0 then
    // substr not found at all
    Result := False
  else
    // found, now check whether substr is at the end of str
    Result := P + Length(substr) - 1 <> Length(str);
end;
Run Code Online (Sandbox Code Playgroud)

  • @RBA我认为Pos是作为对PosEx的调用而实现的.当我阅读问题时,搜索需要从字符串的开头开始.代码也可以用字符串帮助器编写. (2认同)
  • @DavidHeffernan你的单行将不会像OP想要的那样工作.为什么?因为它会将任何以某个子字符串结尾的字符串标记为无效,即使它们确实包含中间某处的特定子字符串.所以正确的答案是你的第一个代码示例. (2认同)