"ABC".charAt(1) then returns the value 'B'. If s has the value "abc", then the expression s.toUpperCase().charAt(1) will be evaluated as follows: ![]() It will then execute using the value returned by the first call as its implicit object. Java will first execute using as its implicit object parameter. public static void printLocations ( char c, String s) In the second method, the constant NOT_FOUND is set to -1, the value returned be indexOf if it fails to find the specific character. The first method uses charAt to examine every character while the second method uses indexOf to jump to the locations in which the character occurs. To illustrate how these methods can be used, the next example shoes two ways that we could perform a simple task involving strings.īoth versions of method printLocations print the indices in the string s of the locations that contain the character c. As before, it returns -1 if no such occurrence exists. This form of the method returns the index of the first occurrence of c that has index at least equal to i. The type of argument passes to indexOf is normally char but the method permits the use of an arguments of any integer type other than long.Īnother version of indexOf is useful if we do not necessarily want the leftmost occurrence of a character. If c is a character in the string, the method returns the index of the leftmost occurrence of c if c does not occur in the string, the method returns -1. This method searches its implicit String object from left to right for an occurrence of c. The method is overloaded with the simplest version having the following header: public int indexOf ( char c) The method indexOf enables us to locate a particular character in a string. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |