String Class

Package: java.lang

In Java, strings are reference types based on the String class, not value types like int or boolean. As a result, a string variable holds a reference to an object created from the String class, not the value of the string itself.

Java lets you create strings as if they were primitive types, by assigning a string literal to a String variable, like this:

String greeting = “Hello, World!”;

Note that in Java, a String object is immutable, which means that it can’t be changed. Thus, none of the methods of the String class actually changes the value of a String object. Instead, they manipulate the value of the String object and return a new String object that is a variation of the original string.

Constructors

Method

Description

String()

Creates a new empty string.

String(String original)

Creates a new String object whose value is identical to original.

String(StringBuilder builder)

Creates a new String object whose value is identical to builder.

Methods

Method

Description

char charAt(int index)

Returns the character at the specified position in the string.

int compareTo(String anotherString)

Compares this string with another string, using alphabetical order. Returns –1 if this string comes before the other string, 0 if the strings are the same, and 1 if this string comes after the other string.

int compareToIgnore Case(String anotherString)

Similar to compareTo but ignores case.

boolean contains (CharSequence s)

Returns true if this string contains the parameter value. The parameter can be a String, StringBuilder, or StringBuffer.

boolean endsWith(String suffix)

Returns true if this string ends with the parameter string.

boolean equals(Object anObject)

Returns true if this string has the same value as the parameter string.

boolean equalsIgnoreCase(String anotherString)

Similar to equals but ignores case.

int indexOf(char ch)

Returns the index of the first occurrence of the char parameter in this string. Returns –1 if the character isn’t in the string.

int indexOf(String str)

Returns the index of the first occurrence of the String parameter in this string. Returns –1 if the string isn’t in this string.

int indexOf(String str, int start)

Similar to indexOf, but starts the search at the specified position in the string.

int lastIndexOf(char)

Returns the index of the last occurrence of the char parameter in this string. Returns –1 if the character isn’t in the string.

int lastIndexOf(String str)

Returns the index of the last occurrence of the String parameter in this string. Returns –1 if the string isn’t in this string.

int lastIndexOf(String str, int start)

Similar to lastIndexOf, but starts the search at the specified position in the string.

int length()

Returns the length of this string.

boolean matches(String regex)

Returns true if the string matches the specified regular expression. For more information, see Regular Expressions.

String replace(char oldChar, char newChar)

Returns a new string that’s based on the original string, but with every occurrence of the first parameter replaced by the second parameter.

String replaceAll(String old, String new)

Returns a new string that’s based on the original string, but with every occurrence of the first string replaced by the second parameter. Note that the first parameter can be a regular expression.

String replaceFirst(String old, String new)

Returns a new string that’s based on the original string, but with the first occurrence of the first string replaced by the second parameter. Note that the first parameter can be a regular expression.

String[] split(String regex)

Splits the string into an array of strings, using the string parameter as a pattern to determine where to split the strings.

boolean startsWith(String prefix)

Returns true if this string starts with the parameter string.

boolean startsWith(String prefix, int offset)

Returns true if this string contains the parameter string at the position indicated by the int parameter.

String substring(int start)

Extracts a substring from this string, beginning at the position indicated by the int parameter and continuing to the end of the string.

String substring(int start, int len)

Extracts a substring from this string, beginning at the position indicated by the first parameter and ending at the position one character before the value of the second parameter.

char[] toCharArray()

Converts the string to an array of individual characters.

String toLowerCase()

Converts the string to lowercase.

String toString()

Returns the string as a String. (Pretty pointless, if you ask me, but all classes must have a toString method.)

String toUpperCase()

Converts the string to uppercase.

String trim()

Returns a copy of the string with all leading and trailing white spaces removed.

String valueOf(primitiveType)

Returns a string representation of any primitive type.

Finding the length of a string

The length method returns the length of a string:

String s = “A wonderful day for a neighbor. “;

int len = s.length();

Here, len is assigned a value of 30 because the string s consists of 30 characters.

Getting the length of a string usually isn’t very useful by itself, but the length method often plays an important role in other string manipulations, as you see throughout the following sections.

Making simple string modifications

Several of the methods of the String class return modified versions of the original string. toLowerCase, for example, converts a string to all-lowercase letters:

String s = “Oompa Loompa”;

s = s.toLowerCase();

Here, s is set to the string oompa loompa. The toUpper Case method works the same way but converts strings to all-uppercase letters.

The trim method removes white-space characters (spaces, Tabs, new lines, and so on) from the start and end of a word. Here’s an example:

String s = “ Oompa Loompa “;

s = s.trim();

Here, the spaces before and after Oompa Loompa are removed. Thus, the resulting string is ten characters long.

Extracting characters from a string

The charAt method extracts a character from a specific position in a string. Remember that the index number for the first character in a string is 0, not 1. Also, you should check the length of the string before extracting a character. If you specify an index value that’s beyond the end of the string, the unchecked exception StringIndexOutOfBoundsException is thrown.

Here’s an example of a program that uses the charAt method to count the number of vowels in a string:

public int CountVowels(String str)

{

int vowelCount = 0;

for (int i = 0; i < str.length(); i++)

{

char c = str.charAt(i);

if ( (c == ‘A’) || (c == ‘a’)

|| (c == ‘E’) || (c == ‘e’)

|| (c == ‘I’) || (c == ‘i’)

|| (c == ‘O’) || (c == ‘o’)

|| (c == ‘U’) || (c == ‘u’) )

vowelCount++;

}

return vowelCount;

}

Here, the for loop checks the length of the string to make sure that the index variable i doesn’t exceed the string length. Then each character is extracted and checked with an if statement to see whether it is a vowel. The condition expression in this if statement is a little complicated because it must check for five different vowels, both uppercase and lowercase.

Extracting substrings from a string

The substring method lets you extract a portion of a string. This method has two forms. The first version accepts a single integer parameter. It returns the substring that starts at the position indicated by this parameter and extends to the rest of the string. (Remember that string positions start with 0, not 1.) For example:

String s = “Baseball”;

String b = s.substring(4); // “ball”

Here, b is assigned the string ball.

The second version of the substring method accepts two parameters to indicate the start and end of the substring you want to extract. Note that the substring actually ends at the character that’s immediately before the position indicated by the second parameter. So to extract the characters at positions 2 through 5, specify 1 as the start position and 6 as the ending position. For example:

String s = “Baseball”;

String b = s.substring(2, 6); // “seba”

Here, b is assigned the string seba.

Splitting a string

The split command is especially useful for splitting a string into separate strings based on a delimiter character. Suppose that you have a string with the parts of an address separated by colons, like this:

1500 N. Third Street:Fresno:CA:93722

With the split method, you can easily separate this string into an array of four strings representing each part of the address. In the process, the colons are discarded. For example:

String address =

“1500 N. Third Street:Fresno:CA:93722”;

String[] parts = address.split(“:”);

String street = parts[0];

String city = parts[1];

String state = parts[2];

String zipcode = parts[3];

The string passed to the split method is actually a special type of string used for pattern recognition — a regular expression. For more information, see Regular Expressions.

Replacing parts of a string

You can use the replaceFirst or replaceAll method to replace a part of a string that matches a pattern you supply with some other text. For example:

String s1 = “I love cats. Cats are best.”;

String s2 = s1.replaceAll(“cats”, “dogs”);

When the second line is executed, s2 will be assigned the value I love dogs. Dogs are the best.

As with the split methods, the first parameter of replace methods can be a regular expression that provides a complex matching string. (For more information, see Regular Expressions.)

Matching a regular expression

The matches method can be used to determine whether a given string matches a regular expression. For example:

String pattern = “b{aeiou}t”;

String test = “bat”;

bool match = test.matches(pattern); // true

For more information, see Regular Expressions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset