Thursday, October 27, 2011

Useful Methods of the String Class in Java

We shall consider a string called stringTest which contains the data "The bird is the word":
String stringTest = "The bird is the word";
The string can be represented as (the upper row represent the index of the character and the lower row contains the characters):

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
T
h
e

b
i
r
d

i
s

t
h
e

w
o
r
d

1.Getting a character at a certain specified position
The function charAt(int index) returns the character at a certain index. One must note that the characters in a string are counted from 0 to length-1, not from 1 to length.
char c2 = stringTest.charAt(2); 
//c2='e'
You can also return the char as an int using codePointAt(int index). The returned integer represents the character's Unicode.
int i2 = stringTest.codePointAt(2); 
//i2=84
2.Comparing strings
To check if two strings represent the same thing you need to use the equals(String str) (uppercase and lowercase letters are not equivalent) or equalsIgnoreCase(String str) (ignores if letters are uppercase or lowercase). Using == is not correct, because == is used to compare references (addresses situated in the program's memory.
boolean be = stringTest.equals("THE BIRD IS THE WORD"); 
//be is false
boolean bc = stringTest.equalsIgnoreCase("THE BIRD IS THE WORD"); 
//bc is false
To compare strings (check if one string is "greater" or "lower" than other string), one must use the compareTo(String str) or the compareToIgnoreCase(String str). The difference between this methods is the same as in equals and equalsIgnoreCase. In both methods strings are compared lexicographically.
int ce = stringTest.compareTo("THE BIRD IS THE WORD");
//ce = 32
int cc = stringTest.compareToIgnoreCase("THE BIRD IS THE WORD");
//ce = 0  
You can also check out if a certain region of an string is the same as a certain region of another string using the methods regionMatches(int primaryStringOffset,String secondaryString, int substringOffset, int lengthOfRegion) or regionMatches(boolean ignoreCase, int primaryStringOffset,String secondaryString, int substringOffset, int lengthOfRegion). 

In the example below our primary string is stringTest ("The bird is the word") and our secondaryString is "bird is the word" (respectively "BIRD is the word"). The method will take the primary string substring starting at index 4 and ending at index 4+4 and the secondary string substring starting at index 0 and ending at index 0+4. The taken substrings will be compared lexicographically. If the substrings are identical the method will return true. Otherwise the method will return false.
boolean brm1 = stringTest.regionMatches(4, "bird is the word", 0, 4);
//true
boolean brm2 = stringTest.regionMatches(true, 4, "BIRD is the word", 0, 4);
//true
3.Concatenating strings
To concatenate a string with another string or another object (who has a toString() method defined) you can use the + operator.
String myString = "The bird" + " is the word in " + 2011;
Alternatively, you could use concat(String str)
String myString = "The bird is the ";
myString = myString.concat("the word in ");
myString = myString.concat(""+2011);
The easiest way to concatenate with an object that is not a string, is to add to that object an empty string (as in code example above).
4.Searching in a string
The String class has various methods for checking if a string contains a certain substring.
Searching if a string contains a substring
boolean bt = stringTest.contains("bird");
//true
Searching if the string starts with a certain substring (prefix)
boolean s2 = stringTest.startsWith("bird");
//true
Searching if the string ends with a certain substring (suffix)
boolean s1 = stringTest.endsWith("word");
//true
Also, by using the String class, you can determine the first occurrence or the last occurrence of a certain substring (optionally you can also specify a starting index for the search). These methods will return the starting index of the substring.
int s3 = stringTest.indexOf("bird",0);
//4
int s4 = stringTest.lastIndexOf("word", 23);
//16
5.Other operations
Checking if a string is empty (has the length equal to 0).
boolean b = stringTest.isEmpty(); 
//false
Getting the length of a string.
int l = stringTest.length(); 
//20
Replace all occurrences of a certain specified substring
String st1 = stringTest.replaceAll("The bird", "Homer Simpson");
//Homer Simpson is the word
Replacing the first occurrence of a substring
String stringTest2 = "Bird, Bird, Bird is the word";
String st2 = stringTest.replaceFirst("Bird", "Homer Simpson");
//Homer Simpson, Bird, Bird is the word"
Dividing a string in multiple substrings. The dividing is determined by a regex (a substring). The method returns an array of String.
String stArray[] = stringTest.split(" ");
//The
//bird
//is
//the
//word
Getting a string of a substring by specifying the first and last index
String st3 = stringTest.substring(0, 8);
//The bird
Transform the string to uppercase/lowercase
String st4 = stringTest.toLowerCase();
//the bird is the word
String st5 = stringTest.toUpperCase();
//THE BIRD IS THE WORD
Eliminating all whitespace from begining and end.
String stringTest3="         The bird is the word           ";
String st6 = stringTest3.trim();
//The bird is the word

LATER EDITS:
29.12.2011 : Added description for the regionMatches(...) method. Corected some mistakes.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger