Skip to main content
ICT
Lesson A10 - The String Class
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

E. String Query Methods page 7 of 17

Query Method
Sample Syntax
int length(); String str1 = "Hello!";
int len = str1.length(); // len == 6
char charAt(int index); String str1 = "Hello!";
char ch = str1.charAt(0); // ch == 'H'
int indexOf(String str); String str2 = "Hi World!";
int n = str2.indexOf("World"); // n == 3
int n = str2.indexOf("Sun"); // n == -1
int indexOf(char ch); String str2 = "Hi World!";
int n = str2.indexOf('!'); // n == 8
int n = str2.indexOf('T'); // n == -1
  1. The int length() method returns the number of characters in the String object.

  2. The charAt method is a tool for extracting a character from within a String. The charAt parameter specifies the position of the desired character (0 for the leftmost character, 1 for the second from the left, etc.). For example, executing the following two instructions prints the char value 'X'.

    String stringVar = "VWXYZ"
    System.out.println(stringVar.charAt(2));

  3. The int indexOf(String str) method will find the first occurrence of str within this String and return the index of the first character. If str does not occur in this String, the method returns -1.

  4. The int indexOf(char ch) method is identical in function and output to the other indexOf function except it is looking for a single character.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.