PDA

View Full Version : does string have valid chars



xGTx
25-05-2005, 02:58 AM
I was writing some code that will check each character of a string against a "character map" to decide if the string had any invalid chars in it. After i was done, I decided there has to be a better way. But im brain dead right now and cant think and its bugging me so much, so i turned here. What do you guys think...

Here's what i have now, can it be done better:

Const VALID_CHARS_MAP_1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ';


function ValidChars(Str : String; Map : String) : Boolean;
var i,k : integer;
Continue : Boolean;
begin
Result := False;

if Length(Str) < 1 then Exit;
if Length(Map) < 1 then Exit;

Continue := True;

for i := 0 to Length(Str) - 1 do
begin
if Continue = False then Exit;
Continue := False;
for k := 0 to Length(Map) - 1 do
begin
if Str[i] = Map[k] then
begin
Continue := True;
break;
end;
end;
end;
Result := True;
end;

Traveler
25-05-2005, 07:48 AM
Here's what i have now, can it be done better:


Ah well yes, there's a much faster/easier way.

procedure TForm1.Button1Click(Sender: TObject);
var allGoodChars : boolean;
x: byte;
text : string;
begin
//our sample string
text := 'Hello Pascal';
allGoodChars := true;
for x := 1 to length(text) do
//check for a-z, A-Z and a space
if not (text[x] in ['a'..'z', 'A'..'Z', ' ']) then
begin
allGoodChars := false;
exit;
end;
//display result
if allGoodChars then
showmessage('All good')
else
showmessage('Wrong char found')
end;

Hope this helps

Traveler
25-05-2005, 07:56 AM
Here's the same script but written so you can easily copy/past it :)

function checkCharsInString(text: string): boolean;
var x : word;
begin
result := true;
for x := 1 to length(text) do
if not (text[x] in ['a'..'z', 'A'..'Z', ' ']) then
begin
result := false;
exit;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if checkCharsInString('hello Pascal') then
showmessage('All good')
else
showmessage('Wrong char found')
end;

xGTx
25-05-2005, 04:54 PM
Ah, thanks a bunch! I ever really understood exactly how the "in" operator works. But i guess it tests an element with a group of elements huh?

Clootie
26-05-2005, 04:31 PM
For general case it will be easier and speedier to use Pos function:
Continue:= Pos(Str[i], VALID_CHARS_MAP_1) <> 0;

Crisp_N_Dry
26-05-2005, 04:34 PM
You're right about the In operator but just in case anyone didn't know it can only check within a range of 0 to 255, which makes it ideal for characters since the range is 256 but it wouldn't be useful if you wanted to use it for collision detection say.