2012-12-04 77 views

回答

7

您可以使用IndexStrStrUtils返回-1如果未找到字符串例如

Caption := IntToStr(
    IndexStr(FormatSettings.LongMonthNames[7], FormatSettings.LongMonthNames) + 1); 

編輯:
爲了避免與鑄造和大小寫問題,你可以使用IndexText如圖所示:

Function GetMonthNumber(Const Month:String):Integer; overload; 
begin 
    Result := IndexText(Month,FormatSettings.LongMonthNames)+1 
end; 
+0

(或者ANSIText的情況下,函數不敏感)。我不會這樣做,因爲那時我必須強制使用字符串<-> ANSIString,並且我的代碼在所有括號中都變得難以理解;-)我將授予這個答案,但不會將其標記爲'正確答案。並感謝您的努力。 –

0

我不能找到一種方法,但我寫一個。 ;-)

function GetMonthNumberofName(AMonth: String): Integer; 
var 
    intLoop: Integer; 
begin 
    Result:= -1; 
    if (not AMonth.IsEmpty) then 
    begin 
    for intLoop := Low(System.SysUtils.FormatSettings.LongMonthNames) to High(System.SysUtils.FormatSettings.LongMonthNames) do 
    begin 
     //if System.SysUtils.FormatSettings.LongMonthNames[intLoop]=AMonth then --> see comment about Case insensitive 
     if SameText(System.SysUtils.FormatSettings.LongMonthNames[intLoop], AMonth) then 
     begin 
     Result:= Intloop; 
     Exit 
     end; 
    end; 
    end; 
end; 

好吧,我改變這個功能爲其他FormatSettings。

function GetMonthNumberofName(AMonth: String): Integer; overload; 
function GetMonthNumberofName(AMonth: String; AFormatSettings: TFormatSettings): Integer; overload; 

function GetMonthNumberofName(AMonth: String): Integer; 
begin 
    Result:= GetMonthNumberofName(AMonth, System.SysUtils.FormatSettings); 
end; 

function GetMonthNumberofName(AMonth: String; AFormatSettings: TFormatSettings): Integer; 
var 
    intLoop: Integer; 
begin 
    Result:= -1; 
    if (not AMonth.IsEmpty) then 
    begin 
    for intLoop := Low(AFormatSettings.LongMonthNames) to High(AFormatSettings.LongMonthNames) do 
    begin 
     if SameText(AFormatSettings.LongMonthNames[intLoop], AMonth) then 
     begin 
     Result:= Intloop; 
     Exit 
     end; 
    end; 
    end; 
end; 

與電話系統formatsetting

GetMonthNumberofName('may'); 

或FormatSetting

procedure TForm1.Button4Click(Sender: TObject); 
var 
    iMonth: Integer; 
    oSettings:TFormatSettings; 
begin 
    // Ned 
    // oSettings:= TFormatSettings.Create(2067); 
    // Fr 
    // oSettings:= TFormatSettings.Create(1036); 
    // Eng 
    oSettings:= TFormatSettings.Create(2057); 
    iMonth:= GetMonthNumberofName(self.Edit1.Text, oSettings); 
    showmessage(IntToStr(iMonth)); 
end; 
+1

我可能會做一個不區分大小寫的比較,使用SameText而不是「=」。另外,這個函數的重載版本需要TFormatSettings參數呢? – dummzeuch

+0

@dummzeuch:我不明白超載的功能? – Ravaut123

+0

function GetMonthNumberofName(AMonth:String):Integer;超載; 函數GetMonthNumberofName(AMonth:String; AFormatSettings:TFormatSettings):Integer;超載; 第二個變體使用給定的AFormatSettings參數而不是System.SysUtils.FormatSettings來滿足程序需要對不同於操作系統中配置的語言環境進行轉換的情況。 (對不起,,評論不允許換行。) – dummzeuch

相關問題