Java Reference
In-Depth Information
Searching for a String
You can get the index of a character or a string within another string using the
indexOf()
and
lastIndexOf()
methods. For example,
String str = new String("Apple");
int index;
index = str.indexOf('p'); // index will have a value of 1
index = str.indexOf("pl"); // index will have a value of 2
index = str.lastIndexOf('p'); // index will have a value of 2
index = str.lastIndexOf("pl"); // index will have a value of 2
index = str.indexOf("k"); // index will have a value of -1
The
indexOf()
method starts searching for the character or the string from the start of the string and returns the
index of the first match. The
lastIndexOf()
method matches the character or the string from the end and returns
the index of the first match. If the character or string is not found in the string, these methods return -1.
Representing Values as Strings
The
String
class has an overloaded
valueOf() static
method. It can be used to get the string representation of the
values of any primitive data type or any object. For example,
String s1 = String.valueOf('C'); // s1 has "C"
String s2 = String.valueOf("10"); // s2 has "10"
String s3 = String.valueOf(true); // s3 has "true"
String s4 = String.valueOf(1969); // s4 has "1969"
Getting a Substring
You can use the
substring()
method to get a sub-part of a string. This method is overloaded. One version takes the
start index as the parameter and returns a substring beginning at the start index to the end of string. Another version
takes the start index and the end index as parameters. It returns the substring beginning at the start index and one less
than the end index. For example,
String s1 = "Hello".substring(1); // s1 has "ello"
String s2 = "Hello".substring(1, 4); // s2 has "ell"
Trimming a String
You can use the
trim()
method to remove all leading and trailing whitespaces and control characters from a string.
In fact, the
trim()
method removes all leading and trailing characters from the string, which have Unicode value less
than
\u0020
(decimal 32). For example,
" hello ".trim()
will return
"hello"
•
"hello ".trim()
will return
"hello"
•
"\n \r \t hello\n\n\n\r\r"
will return
"hello"
•