Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 302
  • Last Modified:

Comparing characters before a space in a string

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
Cerixus
Asked:
Cerixus
  • 4
  • 3
  • 2
  • +3
1 Solution
 
Russell LibbySoftware Engineer, Advisory Commented:

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
 
CerixusAuthor Commented:
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
 
Mohammed NasmanSoftware DeveloperCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
snehanshuCommented:
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
 
CerixusAuthor Commented:
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
 
snehanshuCommented:
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
 
snehanshuCommented:
>>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
 
CerixusAuthor Commented:
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
 
TheLeaderCommented:
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
 
DeerBearCommented:
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
 
CerixusAuthor Commented:
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
 
TheLeaderCommented:
well, thank you Cerixus :)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 3
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now