我需要一些帶 Delphi 的計算器,有時我的數字包括'<'和'>'。我需要存盤它們以備后用。例如:
fnc_ProcessNumber('0.320>','100',multiplication)
這需要給出這個輸出:320>,但這一行失敗:
boolControl := ContainsText(strEnteredResult,[lessThan,greaterThan]);
我也試試這個:
boolControl := IndexStr(strEnteredResult,[lessThan,greaterThan]);
這是我的代碼和型別。
type TMaths = (addition,subtraction,multiplication,division);
function fnc_ProcessNumber(strEnteredResult,strProcessedNumber:string;Math:TMaths) : string;
const lessThan : string = '<';
const greaterThan : string = '>';
var
intIndexCounter,intIndexMath:Integer;
extNewResult:Extended;
boolControl,boolLess,boolGreater:Boolean;
begin
Result := 'null';
boolControl := ContainsText(strEnteredResult,[lessThan,greaterThan]);
if boolControl then
begin
case intIndexCounter of
0:
begin
intIndexMath := AnsiPos(lessThan,strEnteredResult);
boolLess := True;
end;
1:
begin
intIndexMath := AnsiPos(greaterThan,strEnteredResult);
boolGreater := True;
end;
end;
strProcessedNumber := Copy(strEnteredResult,intIndexMath,1);
end
else
begin
extNewResult := StrToFloat(strEnteredResult);
end;
case Math of
addition:
begin
extNewResult := extNewResult StrToFloat(strProcessedNumber);
end;
subtraction:
begin
extNewResult := Abs(extNewResult - StrToFloat(strProcessedNumber));
end;
multiplication:
begin
extNewResult := extNewResult * StrToFloat(strProcessedNumber);
end;
division:
begin
extNewResult := extNewResult / StrToFloat(strProcessedNumber);
end;
end;
Result := FloatToStr(extNewResult);
if boolLess then Result := lessThan Result;
else if boolGreater then Result := Result greaterThan;
end;
uj5u.com熱心網友回復:
好吧,ContainsText顯然不能使用,因為它的第二個引數是單個字串,而不是字串陣列。
AndIndexStr也不能使用,因為它只是測驗文本是否(恰好)是陣列的元素之一;它不做任何子串測驗。此外,它回傳一個整數、匹配項的索引或 -1,因此您需要將結果與結果進行比較<> -1以獲得布林值。或者,您可以使用MatchStrwhich 為您執行此測驗。
最后,ContainsText不區分大小寫,IndexStr而不區分大小寫。這是更好地比較ContainsText與IndexText/MatchText和ContainsStr使用IndexStr/ MatchStr:
| 區分大小寫 | 不區分大小寫 | |
|---|---|---|
| 在字串中找到子字串? | ContainsStr |
ContainsText |
| 字串陣列中字串的索引。 | IndexStr |
IndexText |
在字串陣列中找到字串?( Index <> -1) |
MatchStr |
MatchText |
因此,這些函式都不會測驗 (1) 字串是否是字串陣列中任何字串的子字串,或 (2) 字串陣列中的任何字串是否是給定字串的子字串。
但是當然,撰寫這樣的函式完全是微不足道的。這是第二種情況:
function ContainsAnyStr(const AText: string; const AStrings: array of string): Boolean;
begin
for var i := 0 to High(AStrings) do
if ContainsStr(AText, AStrings[i]) then
Exit(True);
Result := False;
end;
function ContainsAnyText(const AText: string; const AStrings: array of string): Boolean;
begin
for var i := 0 to High(AStrings) do
if ContainsText(AText, AStrings[i]) then
Exit(True);
Result := False;
end;
此外,由于您的字串陣列實際上是一個字符陣列,您可以使用TStringHelper.IndexOfAny:
'123>'.IndexOfAny(['<', '>']) <> -1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373133.html
