#include "stdio.h"
#include "string.h"void func(const char *s, char *out)
{
int a,b,c;
char name[10];
sscanf(s,"%d|%d|%[^|]|%d",&a,&b,name,&c);
sprintf(out,"%d%s%d%d",a,name,b,c);
}如何用delphi完成上面的语句
#include "string.h"void func(const char *s, char *out)
{
int a,b,c;
char name[10];
sscanf(s,"%d|%d|%[^|]|%d",&a,&b,name,&c);
sprintf(out,"%d%s%d%d",a,name,b,c);
}如何用delphi完成上面的语句
不过可能对熟悉者就容易一些了(我不是熟悉者)下面我试着把它译成Delphi的代码,必须要声明的是,我只是基本上按照它的原意用Delphi改写的,至于是不是有简便的写法、精练的写法,就不一定了。首先描述一下这个C程序的输出结果:
#include "stdio.h"
#include "string.h" void func(const char *s, char *out)
{
int a,b,c;
char name[10];
sscanf(s,"%d |%d |%[^ |] |%d",&a,&b,name,&c); //从s中分离出a,b,name,c
sprintf(out,"%d%s%d%d",a,name,b,c); //把a,name,b,c输出到out串中
}void main()
{
char *ss="12|5|.. |67";
char *outx[10];
func(ss,outx);
printf("%s",outx); //输出结果:12..567
getch();
}这是我笨到无法再笨的翻译:
type
TMyPChar = array of char; //为了写代码简便暂用了这个procedure func(const sIn: PChar; var sOut: TMyPChar);
var
a,b,c : integer;
name : string;
tempStr: string; //Delphi里增加的临时变量
P : PChar; //Delphi里增加的临时变量
begin P := sIn; tempStr := ''; ////以下几句是截取第1个|前面的数字赋给a
while P^<>'|' do begin
tempStr := tempStr + P^;
Inc(P);
end;
a := StrtoInt(tempStr); Inc(P);
tempStr := ''; ////以下几句是截取第2个|前面的数字赋给b
while True do begin
if P^ = '|' then Break;
tempStr := tempStr + P^;
Inc(P);
end;
b := StrtoInt(tempStr); Inc(P);
tempStr := ''; ////以下几句是截取第3个|或空格前面的字串赋给name
while True do begin
if (P^ = '|') or (P^ = ' ') then Break;
tempStr := tempStr + P^;
Inc(P);
end;
name := tempStr; Inc(P);
tempStr := ''; ////以下几句是截取最后一部分数字赋给c
while True do begin
if (P^ <> '|') and (P^ <> ' ') then
tempStr := tempStr + P^;
if P^ = #0 then Break;
Inc(P);
end;
c := StrtoInt(tempStr); {前面这部分相当于sscanf一句} tempStr := Format('%d%s%d%d', [a, name, b, c]); //以下是合成为一个字串,传给sOut SetLength(sOut, Length(tempStr));
CopyMemory(@sOut[0], @tempStr[1], Length(tempStr)); {上面几句相当于sprintf一句}end;procedure TForm1.Button1Click(Sender: TObject);
const
sssIn = '12|5|.. |67';
var
sssOut : TMyPChar;
begin
func(sssIn, sssOut);
Showmessage(StrPas(@sssOut[0]));
end;