簡體   English   中英

檢查字符串是否包含子字符串,但不包含結尾

[英]Check if string contains substring, but not at the end

delphi中是否有內置函數來查找字符串是否包含子字符串,但包含結尾?

例如,假設我有以下字符串:

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

我想在字符串為G15001 G15005,G15015,PLU15010並且要搜索的子字符串為15時返回true,但是在G14015或PLU14015時返回false,因為它們的末尾只有15。

使用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;

這支班輪應該給您您想要的:

POS(SUBSTR,復制(STR,1,長度(STR)-1))> 0

大衛的解決方案更干凈,但只想做1班輪。

強調單線的更多建議:

function ContainsBeforeEnd(const str, substr: string): Boolean;
begin
  Result := not (Pos(subStr,Str) in [0,Length(str)-Length(subStr)+1]);
end;

function ContainsBeforeEnd(const str, substr: string): Boolean;
begin // Note, string helpers returns results based on zero based strings
  Result := (Length(str) > Length(subStr) and 
    (str.IndexOf(subStr) in [0..Length(str)-Length(subStr)-1]);
end;    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM