2012-12-04 83 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

相关问题