Delphi 从字符串更改为整数

Delphi 从字符串更改为整数,delphi,Delphi,每个人我都需要一些简单的方法来改变Delphi7中的整数和字符串 var Str:String; Int:Integer; // Here what i need to do Str:='123'; Int:=Str.AsInteger // or use this Int:=123; Str=Int.AsString; 您可以使用: StrToInt(s) IntVal := StrToIntDef(StrVal, 42); // will return 42 if StrVal

每个人我都需要一些简单的方法来改变Delphi7中的整数和字符串

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

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


函数。

最简单的方法是使用以下两种方法:

IntVal := StrToInt(StrVal);    // will throw EConvertError if not an integer
StrVal := IntToStr(IntVal);    // will always work
您还可以使用容错性更强的TryStrToInt(远优于捕获
EConvertError
):

如果要使用默认值而不是明确地处理错误,可以使用:

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

如果您使用的是最新版本的Delphi,除了前面的答案之外,您还可以按照最初的想法使用伪OOP语法-命名约定只是ToXXX而不是AsXXX:

Int := Str.ToInteger
Str := Int.ToString;
Integer帮助器还添加了Parse和TryParse方法:

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

对于不安全的强制转换,请使用
strotint
功能,对于安全强制转换,例如
TryStrToInt
。要添加到TLama,还有
strotintdef
和反向转换:-对于SO inter-connectivityTank,您需要,但我不需要那样。。。!看看这个样品<代码>类型TForm1=类(TForm)按钮1:TButton;编辑1:TEdit;程序按钮1点击(发送方:ToObject);终止整数=类值:System.Integer;函数ToString:string;公共属性值:System.Integer读取FValue写入FValue;终止var Form1:TForm1;实现函数Integer.ToString:string;开始Str(FValue,Result);终止程序TForm1.按钮1单击(发送方:TObject);var-op:整数;开始运算值:=45;Edit1.Text:=op.ToString;终止结束。为什么在这里说“pseudo”?在我看来,OOP语法非常简单。我的意思是,在某种程度上,字符串和整数仍然不是OOP意义上的对象(没有继承等)。我不会说OOP需要继承。考虑一个值类型是一个密封类。@ DavidHeffernan:没有任何代码< >创建< /代码>到<代码> STR 或<代码> int >代码>。隐式实例化?好吧,不管怎样。:)@AndriyM
std::string str
您的
按钮1单击时出错:您没有调用
Int
的构造函数。另外,请省略“运行代码片段/复制代码片段以回答”按钮-它们对Delphi代码没有任何用处。@MartynA一开始,一个错误的答案怎么会在三年后成为公认的答案?!编辑我知道是OP干的。
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