简体   繁体   English

从字符串更改为整数

[英]Change from string to integer

EveryOne I need some esay way to change from integer and string in delphi 7 每个人我都需要一种简单的方法来更改delphi 7中的整数和字符串

var 
Str:String;
Int:Integer;
// Here what i need to do
Str:='123';
Int:=Str.AsInteger
// or use this
Int:=123;
Str=Int.AsString;

The easiest way is to use these two methods: 最简单的方法是使用以下两种方法:

IntVal := StrToInt(StrVal);    // will throw EConvertError if not an integer
StrVal := IntToStr(IntVal);    // will always work

You can also use the more fault-tolerant TryStrToInt (far better than catching EConvertError ): 您还可以使用更具容错性的TryStrToInt (远比捕获EConvertError ):

if not TryStrToInt(StrVal, IntVal) then
  begin
  // error handling
  end;

If you want to resort to a default value instead of handling errors explictly you can use: 如果要使用默认值而不是明确处理错误,则可以使用:

IntVal := StrToIntDef(StrVal, 42);    // will return 42 if StrVal cannot be converted

If you're using a recent version of Delphi, in addition to the previous answers, you can alternatively use a pseudo-OOP syntax as you wanted to originally - the naming convention is just ToXXX not AsXXX: 如果您使用的是Delphi的最新版本,除了前面的答案外,您还可以按原本的方式使用伪OOP语法-命名约定只是ToXXX而不是AsXXX:

Int := Str.ToInteger
Str := Int.ToString;

The Integer helper also adds Parse and TryParse methods: 整数帮助器还添加了Parse和TryParse方法:

Int := Integer.Parse(Str);
if Integer.TryParse(Str, Int) then //...

You can use: 您可以使用:

StrToInt(s)

and

IntToStr(i)

functions. 职能。

type 
TForm1 = class(TForm) 
Button1: TButton; 
Edit1: TEdit; 
procedure Button1Click(Sender: TObject); 
end; 

Integer = class 
FValue: System.Integer; 
function ToString: string; 
public 
property Value: System.Integer read FValue write FValue; 
end; 

var 
Form1: TForm1; 

implementation 

function Integer.ToString: string; 
begin 
Str(FValue, Result); 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
var 
Int:integer; 
begin
Int.Value:=45; 
Edit1.Text:=Int.ToString; 
end; 
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM