String search: Difference between revisions

From Cuis CookBook
Jump to navigation Jump to search
(syntax hilight)
No edit summary
 
Line 1: Line 1:


=== Problem ===
=== Problem ===
Search a sub string of some String.
Search a sub-string in some String.


=== Solution ===
=== Solution ===

Latest revision as of 19:59, 12 May 2025

Problem

Search a sub-string in some String.

Solution

Use the String>>findString: methods variations:

  • findString: subString : Answers the index of subString within the receiver, starting at start. If the receiver does not contain subString, answers 0.
  • findString: subString startingAt: anIndex: Same as findString, but starting at index.
  • findString: subString startingAt: anIndex caseSensitive: aBoolean : case sensitive version.

For example:

'foobarbaz' findString: 'foo'. "=> 1" 
'foobarbaz' findString: 'bar'. "=> 4" 
'foobarbaz' findString: 'baz'. "=> 7"

And returns 0 if substring is not found:

'foobarbaz' findString: 'hello' "=> 0"