Locating the first instance of a character
In our programs, the need to find the first occurrence of a character is not uncommon. For example, we may be parsing a large text file and need to break it up into sections, based on an instance of a character. To perform this action, the string
command accepts the keyword first
.
The syntax for the string command is as follows:
string first varString string index
When invoked with the first
keyword, the string
command will search for a character or a sequence of characters in the string. If no match is found, the command returns a -1
. If an index is provided, the search is constrained to the match at (or after) that index within the string.
How to do it…
In the following example, we will locate the first instance of the character a within a string. Return values from the commands are provided for clarity. Enter the following command:
% string first a 123abc123abc 3
How it works…
As you can see, string
has located the first instance of the character...