13

I tried the following code which supposed to check if a string contains spaces but I get an error. How else can I check that

if Index('some string',' ')>1 then begin
   Result:= False;
 end
 else begin
      Result := True;  
 end;
user1016179
  • 599
  • 3
  • 10
  • 24
  • `Index` is the **Extended Pascal – ISO standard 10206** – function. You _are_ using it _correctly_ (presuming you do not consider an _initial_ space as “_contains_ a space”). However, not all processors (that is the specific combination of compiler, operating system, machine architecture, etc.) support this ISO standard. Please specify which processor you are using (in particular which compiler). Besides, `result` directly depends on the Boolean expression’s result, thus `result ≔ index('some string', ' ') ≤ 1` is equivalent to the entire `if`‑`then`-`else` construct. – Kai Burghardt Feb 07 '23 at 13:43

3 Answers3

20

You can use pos function. From documentation:

The pos function returns the position of a substring in a main string. If the substring does not exist in the main string, then the returned value will be 0.

s:='note-book';
x:=pos('book',s); {x will be 6}

All this information, and other useful tips you can find here

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
  • 1
    In that case, how do you know if it contains the string if the string is at the very start? The result will be identical to if the substring was not found. – NickG Feb 11 '15 at 13:54
  • 3
    @NickG Pascal uses 1-based indices, not 0-based. So, pos would return 1 if the needle is at the start of the haystack. – André May 08 '15 at 08:53
5

As an alternative one, AnsiContainsStr can be used for string containing operations.It return True if the string contains the given substring, False otherwise. As an example code:

if AnsiContainStr(mainText, subText) then begin
   //enter here if mainText contains subText.
   //write code for doing needed operations here
end
Mustafa Kemal
  • 1,292
  • 19
  • 24
0

If s is an AnsiString, you can also use s.Contains('foo')

relipse
  • 1,730
  • 1
  • 18
  • 24