[英]Delphi find underline in string
我有兩個名為“ver1”和“ver2”的字符串,字符串中的輸入如下所示:
Ver1: B2CD1
Ver2: B3A10
有時它看起來像這樣:
Ver1: B2CD1_A1
Ver2: B3A10_DE
我的問題:如何在“_”后面的兩個字符串中進行搜索並從中返回一個值?
順便說一下,該功能用於軟件版本比較。 請在我的問題中給我建議,而不是我的全部職能。
謝謝
uses
Classes, SysUtils, StrUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure Memo1Change(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
function isSoftwareGreater(ver1,ver2 : string) : byte;
var i : integer;
tmp1,tmp2 : string;
cver1,cver2 : int64;
begin
{
Return values:
0: versions are equal
1: ver1 is bigger then ver2
2: ver2 is bigger then ver1
253: ver1 is too big (could not be converted to int64)
254: ver2 is too big (could not be converted to int64)
}
tmp1 := '';
tmp2 := '';
for i := 1 to length(ver1) do
begin
if (ver1[i] in ['a'..'z']) or (ver1[i] in ['A'..'Z']) then
tmp1 := tmp1 + inttostr(Ord(ver1[i]));
if (ver1[i] in ['0'..'9']) then
tmp1 := tmp1 + ver1[i];
end;
for i := 1 to length(ver2) do
begin
if (ver2[i] in ['a'..'z']) or (ver2[i] in ['A'..'Z']) then
tmp2 := tmp2 + inttostr(Ord(ver2[i]));
if (ver2[i] in ['0'..'9']) then
tmp2 := tmp2 + ver2[i];
end;
if not TryStrToInt64(tmp2,cver2) then
begin
isSoftwareGreater := 254;
exit;
end;
if not TryStrToInt64(tmp1,cver1) then
begin
isSoftwareGreater := 253;
exit;
end;
if ver1 > ver2 then
isSoftwareGreater := 1
else if ver2 > ver1 then
isSoftwareGreater := 2
else if ver1 = ver2 then
isSoftwareGreater := 0;
end;
您可以使用Pos() 函數搜索字符串。 它返回找到的字符的索引,如果沒有找到則返回 0。
var
Index : Integer;
SubString : String;
begin
Index := Pos('_', Ver1);
if Index > 0 then
SubString := Copy(Ver1, Index + 1, MAXINT)
else
SubString := '';
end;
如果要提取兩個標記之間的文本,則必須按上圖所示搜索第一個,然后從第一個之后開始搜索第二個。 Pos() 有一個可選的第三個參數來指定從哪里開始搜索。 這給出:
var
Index1 : Integer;
Index2 : Integer;
SubString : String;
begin
Index1 := Pos('_', Ver1);
if Index1 > 0 then begin
Index2 := Pos('_', Ver1, Index1 + 1);
if Index2 > 0 then
// We have two underscore, extract text between them
SubString := Copy(Ver1, Index1 + 1, Index2 - Index1 - 1)
else
// Only one underscore, extract text from the first to the end of string
SubString := Copy(Ver1, Index1 + 1, MAXINT);
end
else
SubString := '';
end;
您可以使用ContainsStr()
檢查字符串是否有'_'
,然后使用SubString()
和IndexOf()
function GetString(const AString, ASubString: string): string;
begin
Result:= EmptyStr;
if ContainsStr(AString, ASubString) then
Result:= AString.Substring(Astring.IndexOf(ASubString)+1, AString.Length);
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.