Solved

Comparing characters before a space in a string

Posted on 2003-11-27
12
293 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:mnasman
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
 
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now