Some Built In String Methods
The String Class. Another class you are likely to want to gain some competence with has to do with Strings and their manipulation. The following table contains several methods in the String class. Since these are likely less familiar to you we will present a small program. |
class String in (java.lang package) | |
Method |
Description |
stringName.charAt(n) | Returns the character at
position n in the string. n is an integer, returns a character |
stringName.concat(anotherString) | Concatenates anotherString
to stringName Returns a string |
stringName.indexOf(char) | Returns the position of the
first occurrence of the character in stringName Returns an integer |
stringName.indexOf(string) | Returns the position of the
first occurrence of the string in stringName Returns an integer |
stringName.lastIndexOf(char) | Returns the position of the
last occurrence of the character in stringName Returns an integer |
stringName.lastIndexOf(string) | Returns the position of the
last occurrence of the string in stringName Returns an integer |
stringName.length( ) | Returns the length of
stringName Returns an integer |
stringName.split(string) | Splits stringName around
occurrences of the string Returns a String array |
stringName.substring(bIndex, eIndex) | Returns the substring that
starts at bIndex and ends at eIndex. Returns a String |
stringName.toCharArray( ) | Converts the String to an
array of characters Returns an array of char |
stringName.toLowerCase( ) | Converts the String to lower
case. Returns a String |
object.toString( ) | Converts, if possible, an
object to a String Returns a String |
stringName.toUpperCase( ) | Converts the String to upper
case. Returns a String |
stringName.trim( ) | Trims all leading and
trailing whitespace. Returns a String |
Now you want to run the following application called StringEMail.java. This will require some user interactions. The program does some simple validation about whether a user has input a valid e-mail address. |
import javax.swing.*; public class StringEMail {
} |
We will explain the code in more detail after you run
it. You should compile the code and execute it with the following inputs.
Notice how Microsoft code senses @ symbols in order to determine e-mail addresses. The following images relate to the third input. |
In general, you should know that a
stringName.indexOf(ch) and
stringName.lastIndexOf(ch) return -1
if the character isn't present in the string. We will skip over the initial declarations and initializations. We will also assume you are used to obtaining inputs from users. Now the code can be observed to do the following.
The next webpage will focus on methods for working with characters. |