Solved

Comparing characters before a space in a string

Posted on 2003-11-27
12
297 Views
Last Modified: 2010-04-05
Here's my code:
------------------------------------------------------------
    If LeftStr(CommBlockIn.Msg1,1) = '/' then begin
      i := pos(' ', CommBlockIn.Msg1);
      if LeftStr(CommBlockIn.Msg1,i) = '/test' then begin
        CommBlockOut.Cmd := 'VALCOM';
        CommBlockOut.Msg1 := 'TEST';
        CommBlockOut.Msg2 := 'You issued a test command!';
       end else begin
        CommBlockOut.Cmd := 'INVCOM';
        CommBlockOut.Msg1 := 'Invalid Command!';
        LogMemo1.Lines.Add('Unrecongnized command from '+ CommBlockIn.UserName);
       end;
      Send(Socket.SocketHandle, CommBlockOut, SizeOf(CommBlockOut), 0);
    end
------------------------------------------------------------

The problem is, i always equals zero.  Say I send a string of "/testing" or "/test", they both return "Invalid Command".  "/test" should return "You issued a test command!".  It's obviously something with the line:
       i := pos(' ', CommBlockIn.Msg1);
because it keeps returning 0 (zero), but I don't know why.  How can I fix it?  Is there a better way to do this?  Keep in mind that I will also want to compare the following word after the initial /test command.
0
Comment
Question by:Cerixus
  • 4
  • 3
  • 2
  • +3
12 Comments
 
LVL 26

Expert Comment

by:Russell Libby
ID: 9833393

The one problem I see is if there is no space char (the string is only composed of "/test"), thus the Pos function would return 0. If you want to test if the command is "/test", and just ends there, or has a white space afterwards, then the following would work for you.

var  lpszMsg:    PChar;
     bValid:     Boolean;
begin

  // Cast as pchar
  lpszMsg:=PChar(CommBlockIn.Msg1);

  // Check first char
  if (lpszMsg^ = '/') then
  begin
     // Increment string pointer
     Inc(lpszMsg);
     // Case insensitive compare against "test"
     bValid:=(StrLIComp(lpszMsg, 'test', 4) = 0);
     // Is the command valid so far?
     if bValid then
     begin
        // Increment string pointer in case you want to continue parsing the string
        Inc(lpszMsg, 4);
        // Should be null or white space terminator
        bValid:=(lpszMsg^ in [#0, #10, #13, #32]);
        // Increment again if still valid, then you can check the following word
        if bValid and (lpszMsg^ <> #0) then Inc(lpszMsg);
        // Could check the next word
        // if StrLIComp(lpszMsg, 'foo', 3) = 0 then
        // begin
        //   ...
        // end;
     end;
     // Was this a valid command?
     if bValid then
     begin
        // Set values
        CommBlockOut.Cmd:='VALCOM';
        CommBlockOut.Msg1:='TEST';
        CommBlockOut.Msg2:='You issued a test command!';
     end
     else
     begin
        // Set values
        CommBlockOut.Cmd:='INVCOM';
        CommBlockOut.Msg1:='Invalid Command!';
        LogMemo1.Lines.Add('Unrecongnized command from '+ CommBlockIn.UserName);
     end;
     // Send the message over the socket
     Send(Socket.SocketHandle, CommBlockOut, SizeOf(CommBlockOut), 0);
  end;

end;

Hope this helps,
Russell
0
 
LVL 1

Author Comment

by:Cerixus
ID: 9833847
Problem:
________________________________

lpszMsg:=PChar(CommBlockIn.Msg1);
________________________________

says it's an "Invalid Typecast".  I've never used PChar, so sorry if this is an easy fix.
0
 
LVL 22

Expert Comment

by:Mohammed Nasman
ID: 9834427
Hello

   If I'm right, you are trying to implement server, if you are using indy 9, then look command hanlder support with tcp server component
or if you use other socket components, I prefer to implement the commad as digits, you can use 3 digits for the command, as /001, /002, and because it's fixed you will not need to check for spaces ot anything else, just compare the first four letters in the msg to check if it's a command

HTH
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:snehanshu
ID: 9834458
Cerixus,
  rllibby's explanation is appropriate, but perhaps what you could do is to check if "i" is zero and if so, set it to the length of the string.
Like:
    If LeftStr(CommBlockIn.Msg1,1) = '/' then begin
      i := pos(' ', CommBlockIn.Msg1);
      if i = 0 then i := length(CommBlockIn.Msg1);//Add this line
...



HTH
...Shu
0
 
LVL 1

Author Comment

by:Cerixus
ID: 9834468
First, I hate Indy ;).  I actually downgraded to Delphi 6 so I could use TServerSocket.

Secondly, it does the above even if I send "/test foo".  But the "if 0 then len" is a good solution to an input of "/test".
0
 
LVL 5

Expert Comment

by:snehanshu
ID: 9834519
Cerixus,
>>Secondly, it does the above even if I send "/test foo".  
Do you mean it does not work even with "/test foo" or that it works with "/test foo" ?
And a few suggestions:
1) I don't have a LeftStr in Delphi 5. Why don't you use Copy(CommBlockIn.Msg1,1,i) instead?
2) Wouldn't you like to take care of case? like
  if Uppercase(Copy(CommBlockIn.Msg1,1,i)) = UpperCase('/test') then
3) And take care of trailing/leading spaces like
  mycmdstr := UpperCase(trim(CommBlockIn.Msg1));
and use mycmdstr for all comparisons instead of CommBlockIn.Msg1?

...Shu
0
 
LVL 5

Expert Comment

by:snehanshu
ID: 9834565
>>Secondly, it does the above even if I send "/test foo".
Because it includes the space also in the comparison.

So,
i := pos(' ', CommBlockIn.Msg1);
I guess you should change it to
i := pos(' ', CommBlockIn.Msg1) -1;
and the if to
 if i < 0 then i := length(CommBlockIn.Msg1);


*** OR ***
if you used my trim suggestion then

i := pos(' ', mycmdstr) -1;
if i < 0 then i := length(mycmdstr);

...Shu
0
 
LVL 1

Author Comment

by:Cerixus
ID: 9834612
Ignore the "secondly" point, I was thinking of a different post.  Sorry.

I can't test any of this due to the fact that when using the code first mentioned in this post I can't compile it.  I keep getting the  "Invalid Typecast" error.
0
 
LVL 2

Accepted Solution

by:
TheLeader earned 500 total points
ID: 9835068
Break ....... ;)
by the way "Cerixus"
TClientSocket and TServerSocket  available in Delphi 7,
To do this go to Component | Install Packages | Add (/bin/dclsockets70.bpl).
Just to let you know
Break....... ;)
0
 
LVL 5

Expert Comment

by:DeerBear
ID: 9837267
Hi,

I think the problem can be solved very easily in this way:

function CheckCommand( Cmds : TStringList;Buffer : String;CmdChar : Char;var CmdPos : Integer ) : Boolean;
var Cmd_Index : Integer;
     Test_Pos : Integer;
begin
   Result := False;
   CmdPos := -1;
   for Cmd_Index := 0 to Pred( Cmds.Count ) do
   begin
      Test_Pos := Pos( Cmds.Strings[ Cmd_Index ],Buffer );
      if Test_Pos > 0 then
      begin
        if Buffer[ Pred( Test_Pos ) ] = CmdChar then
        begin
           CmdPos := Cmd_Index;
           Result := True;
        end;
      end;
   end;
end;

Then you call it in this way:

if CheckCommand( CommandList,'/test','/',CmdPosition ) then
begin
   Command := CommandList.Strings[ CmdPosition ];
end;

Do you like it?

HTH,

Andrew
0
 
LVL 1

Author Comment

by:Cerixus
ID: 9838829
I accepted that answer because it's great information and because I found a different solution to my question.  Someone pointed out in a separate question that Strings are nothing more than arrays of characters (duh).  Using that information, I can dissect the strings easily in any way I please.

Thank you all for your help though.
0
 
LVL 2

Expert Comment

by:TheLeader
ID: 9839972
well, thank you Cerixus :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question