Solved

Comparing characters before a space in a string

Posted on 2003-11-27
12
296 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

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.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Machine not responding during CopyFile() 3 103
Delphi TcxGrid group footer summary 3 314
Delphi IDE crash without error message ... 7 99
PHP preg_replace code convert to Delphi 14 66
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

792 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