?
Solved

Comparing characters before a space in a string

Posted on 2003-11-27
12
Medium Priority
?
300 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1500 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
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…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

718 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