Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)

10.4 Finding the Position of a Substring

To get the position of a substring within a string is very similar to that of a character. The operator indexof is also used to search for substrings. This operator searches the string from left to right. This operator is also used in an assignment statement. The general structure of this statement with the indexof operator follows.

set 〈 int_var 〉 = indexof 〈 str_var1 〉 of 〈 str_var2 〉

For example, to get the index value in string variable message for the substring "llo" and assign this to integer variable num, the complete statement is:

variable integer num string mystr = "llo" ... set num = indexof mystr of message

When this statement executes, the value of variable num becomes 9. If the starting index value is known, it can be included after the substring in the assignment statement. If the substring indicated does not exist in the string, then the value assigned is - 1.

Категории