开发者

What's wrong with this code to un-camel-case a string?

Here is my attempt to solve the About.com Delphi challenge to un-camel-case a string.

unit challenge1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
   check = 65..90;
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  var s1,s2 :string;
  int : integer;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  i:开发者_如何学运维 Integer;
  checks : set of check;
begin
  s1 := edit1.Text;
  for i := 1 to 20  do
  begin
    int  :=ord(s1[i]) ;
    if int in checks then
      insert('  ',s1,i-1);
  end;
  showmessage(s1); 
end;

end.

check is a set that contains capital letters so basically whenever a capital letter is encountered the insert function adds space before its encountered (inside the s1 string), but my code does nothing. ShowMessage just shows text as it was entered in Edit1. What have I done wrong?


You're correct that check is a set, but you haven't assigned any value to it yet, so its value is indeterminate. There are not the characters you expect in it, so the in test probably always fails. (Didn't the compiler warn you that you hadn't assigned anything check yet?)

You don't really want to define check as a subrange type. Rather, you should replace check with the built-in TSysCharSet type, which is a set of characters. Then assign check like this:

check := ['A'..'Z'];

Furthermore, rather than check the numeric value of the string with int and Ord, just use the Char values directly: if s1[i] in check. You'll also want to use the Length function so you process the entire string instead of assuming that the input will always be exactly 20 characters long. You'll also want to store the result into something other than s1 since, as Caldon points out, you don't want to modify it at the same time that you're still reading more characters from it.


if you try your program on e.g. string "MyText", then in the first loop it correctly recognizes that "M" is capital, and so it enters one space before it... so the string is " MyText"... now in the next loop, i=2, and s1[i] is again "M" and so it inserts one space before it... and so on...


checks is local to the method and never initialized. It may contain random data, but most probably not the data you expect (perhaps it it is an empty set). So the IF-condition will probably never become true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜