我必须阅读未知数量的单词并在单词" last"键入。 我必须:
问题:我唯一的问题是显示以" anne"结尾的名字数量。它显示0,除非我只输入单词" anne",然后显示1。
注意:
我的代码:
unit Ess_U;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
redOut: TRichEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
Var wrd : string;
Scount, dcount, Namecount : integer;
begin
redOut.clear;
Scount := 0;
dcount := 0;
Namecount := 0;
repeat
wrd := inputbox ('Input words', 'Enter any word', '');
if (Pos('S',wrd) > 0) AND (wrd[1] = 'S') then
begin
inc(Scount);
end
else if (Pos('d',wrd) > 0) AND (wrd[length(wrd)] = 'd') then
begin
inc(dcount);
end
else if copy(wrd, length(wrd)-4,4) = 'anne' then
begin
inc(Namecount);
end;
until (wrd = 'last');
redOut.Lines.Add ('The number of names that begin with the letter "S" is ' + inttostr(Scount));
redOut.Lines.Add ('The number of names that end with the letter "d" is ' + inttostr(dcount));
redOut.Lines.Add ('The number of names that begin with "anne" is ' + inttostr(Namecount));
end;
end.
enter code here
答案 0 :(得分:6)
您已经有了一个答案,向您展示了使用库函数执行您尝试的操作的另一种方法。这很好(假设你的Delphi版本有它们),但是你的问题有一个未解决的方面。
你说“问题:我唯一的问题是显示以”anne“结尾的名字数量。它显示0,除非我只输入单词”anne“,否则显示1。”
现在,编码的关键部分是学习调试,其中一个关键部分是准确观察并知道构建可重现的测试用例。
试试这个:
将repeat
循环的第一行更改为:
wrd := 'xanne'; //inputbox ('Input words', 'Enter any word', '');
并将'anne'的测试更改为
else begin
wrd := copy(wrd, length(wrd)-4,4);
Caption := wrd;
if wrd = 'anne' then
begin
inc(Namecount);
end;
end;
然后,在行上放置一个断点
wrd := copy(wrd, length(wrd)-4,4);
并按F9
编译并运行您的程序。
当调试器在断点处停止时,继续按F8
(单步执行代码。
你很快就会发现什么是错的,即
copy(wrd, length(wrd)-4,4)
当wrd以'xanne'开头时,不等于'anne'。我会告诉你为什么不这样做,因为我觉得你会发现比找到一个新到你的库函数更有启发性。
顺便说一句,当您尝试通过反复输入输入来测试程序时,会出现这种情况。这就是为什么我说要暂时修改你的代码,以便你从一个已知的输入开始,而不是你输入错误的输入(或者甚至错误地打开CapsLock并且没有注意到)。
答案 1 :(得分:3)
您应该使用StartsText
中的EndsText
和StrUtils
检查字符串是否以文字开头或结尾,而不是手动调用Pos
和{{1} }。 (或Copy
和AnsiStartsText
)
将AnsiEndsText
添加到您的uses子句中,并使用以下条件更改该部分:
StrUtils
...
uses StrUtils, ...;
...
if (StartsText('S', wrd)) then
begin
Inc(Scount);
end
if (EndsText('d', wrd)) then
begin
Inc(dcount);
end
if (StartsText('anne', wrd)) then
begin
Inc(Namecount);
end;
单位具有以下有用的例程:
- StartsText - 确定子字符串
StrUtils
是否以字符串ASubText
开头,不区分大小写的比较;- StartsStr - 与
AText
相同,但区分大小写;- EndsText - 确定子字符串
StartsText
是否结束字符串ASubText
,不区分大小写的比较;- EndsStr - 与
AText
相同,但区分大小写;