Dokumen - Tips 11 String and String Builder Java
Dokumen - Tips 11 String and String Builder Java
MANIPULATION
Contents:
1. What Is String?
2. Creating and Using Strings
Declaring, Initializing, Reading and Printing
3. Manipulating Strings
Comparing, Concatenating, Searching, Extracting Substrings,
Splitting
4. Other String Operations
Replacing Substrings, Deleting Substrings, Changing Character
Casing, Trimming
5. Building and Modifying Strings
Using StringBuilder Class
6. Formatting Strings
WHAT IS STRING?
String is:
A sequence of characters
Each character is a Unicode character
Represented by the String (java.lang.String) data type in Java
Example:
s H e l l o , J a v a
java.lang.String
String s = "Hello!";
int len = s.length(); // len = 6
char ch = s.charAt(1); // ch = 'e‘`
index = 0 1 2 3 4 5
s.charAt(index) = H e l l o !
java.lang.String
Example:
String s = "Hidaya Institute of Science & Tchnology.";
System.out.println("s= "+s);
System.out.println("Length= "+s.length());
Declaring
We use Java String class for declaring string variables:
String str;
Initializing
s1
String
reference Java
variable s1 Is
String Object
String Object
s2
String JavaIs
reference
variable s2 String Object
s1 Is
Java String Object
String
reference String Object
variable s1 JavaIs
String Object
s2
JavaIsFun
String Fun
reference String Object
String Object
variable s2
Comparing Strings:
There are a number of ways to compare two strings:
Dictionary-based string comparison
Case-insensitive
Case-sensitive
str1.compareTo(str2);
COMPARING STRINGS (2)
if (str1.equalsIgnoreCase(str2)){
…
}
i = 0 1 2 3 4 5 6 7 8 9 10 11 12 …
s.charAt(i) = J a v a P r o g r a m m …
EXTRACTING SUBSTRINGS
Extracting substrings
str.substring(int beginIndex, int endIndex)
lastIndex is not included
str.substring(int beginIndex)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
C : \\ P i c s \\ R i l a 2 0 0 5 . j p g
SPLITTING STRINGS
To split a string by given separator(s) use the following
method:
String[] split(String regex)
StringBuilder: H e l l o , J a v a !
length() = 11
capacity() = 15 used buffer unused
(length()) buffer
Using toString()
METHOD toString()
All classes have this public virtual method derived from
Object class
Returns a human-readable, culture-sensitive string representing
the object
Most Java Platform types have own implementation of
toString()