16,748
社区成员
发帖
与我相关
我的任务
分享
const
S: string = '21,33,03,45,31,04,56,66,86,55';
var
nStr: string;
begin
for nStr in S.Split([',']) do
try
if nStr.ToInteger and 1 = 1 then
ShowMessage('奇数')
else
ShowMessage('偶数');
except
ShowMessage('不是有效数字');
end;
end;
//也可以不使用TStringList,下面的写法运行效率更高一点:
procedure TForm1.Button1Click(Sender: TObject);
var
C: AnsiChar;
S: AnsiString;
Found: Boolean;
I, Len, Odd, Even: Integer;
begin
S := '21,33,03,45,31,04,56,66,86,55';
Found := False; Odd := 0; Even := 0; len := Length(S);
for I := 1 to Len do
begin
if S[I] in ['0'..'9'] then
begin
C := S[I];
Found := True;
end;
if Found and ((I = Len) or (not (S[I] in ['0'..'9']))) then
begin
if (C in ['1', '3', '5', '7', '9']) then
Inc(Odd)
else
Inc(Even);
Found := False;
end;
end;
ShowMessage(Format('奇数个数: %d, 偶数个数:%d', [Odd, Even]));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
S: AnsiString;
i,Len, Odd, Even: Integer;
begin
S := '21,33,03,45,31,04,56,66,86,55';
Odd := 0; Even := 0; len := Length(S);
for I := 1 to Len do
begin
if i<Len then
begin
if S[I+1]=',' then
begin
if S[I] in ['1', '3', '5', '7', '9']
then Inc(Odd)
else Inc(Even);
end
end
else begin
if S[I] in ['1', '3', '5', '7', '9']
then Inc(Odd)
else Inc(Even);
end;
end;
ShowMessage(Format('奇数个数: %d, 偶数个数:%d', [Odd, Even]));
end;
uses System.SysUtils, System.StrUtils;
procedure StatNumbers(const S: string; var Odds, Evens: integer);
var
p1, p2, n, c: integer;
begin
Odds := 0;
Evens := 0;
p1 := 1;
p2 := 1;
repeat
if p1 > Length(S) then break;
p2 := PosEx(',', S, p2);
if p2 = 0 then p2 := Length(S) + 1;
Val(Copy(S, p1, p2 - p1).Trim, n, c);
if c = 0 then
if n and 1 <> 0 then Inc(Odds) else Inc(Evens);
p1 := p2 + 1;
p2 := p1;
until false;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
S, T: String;
Odd, Even: Integer;
List: TStringList;
begin
List := TStringList.Create;
S := '21,33,03,45,31,04,56,66,86,55';
List.DelimitedText := S;
Odd := 0; Even := 0;
for T in List do
begin
if (StrToInt(T) mod 2) = 1 then
Inc(Odd)
else
Inc(Even);
end;
List.Free;
ShowMessage(Format('奇数个数: %d, 偶数个数:%d', [Odd, Even]));
end;