Java Programming
CHAPTER 13
Strings and Regular Expressions
Java Programming 1
Contents
Character Sequences
The String Class
Regular Expression Matching
The StringBuilder Class
Java Programming 2
Character Sequences, The String Class
The CharSequence interface
charAt, length, subSequence, toString methods
The String class defines objects that represent such
character sequences.
The CharSequence interface implemented by String,
StringBuilder, StringBuffer
The String Class
Basic Operations
― charAt
― indexOf
for (int I = 0; I endPos) // start after end Running Example:
return null; The invocation
delimitedString(“This is
else
”,‟‟);
return from.substring(starPos, endPos + 1); returns
} .
Java Programming 8
The String Class
Match with a given regular expression
The array elements returned from split(“--”,n) invoked on the string “w--x--y--” for n
eual to -1,0,1,2,3, and 4:
public class RunSplit { split method:
public static void main(String args[]) { String[] split(String regex, int limit)
String str = new String("w--x--y--");
String[] result; limit (when it is n):
n-1 times applied
When n ' ;
sequence of String }
manipulations
When restricted to String quoted =
String expressions String.valueOf(''));
Using StringBuilder
String quoted = new
The compiler uses this StringBuilder().append('').toString();
faster than the String
Java Programming 17
Modifying the Buffer
Replace Method Insert Method
public static void replace(StringBuilder public static StringBuilder
str, char oldChar, char newChar) { addDate(StringBuilder buf) {
for(int i=0; i buf.length()) throw new
IndexOutOfBoundsException();
int leftover = buf.length() – (pos + cnt);
if (leftover == 0) {
buf.setLength(pos);
return buf;
public void getChars(int srcBegin,
} int srcEnd, char[] dst, int dstBegin)
char[] chrs = new char[leftover];
buf.getChars(pos + cnt, buf.length(), chrs, 0);
buf.setLength(pos);
Parameters:
buf.append(chrs); • srcBegin - start copying at this
return buf; offset.
• srcEnd - stop copying at this
} offset.
• dst - the array to copy the data
into.
Java Programming • dstBegin - offset into dst. 19
Capacity Management and The String Buffer Class
Allocate space for the The StringBuffer Class
buffer The StringBuffer class is
String sqrtIntFaster(int i) { essentially identical to the
StringBuilder class except for
StringBuilder buf = new one thing.
StringBuilder(50);
It provides a thread-safe
implementation of an
buf.append(“sqrt(“).append(i).a appendable character
ppend(„)‟); sequence.
buf.append(“ = But the StringBuilder is faster
“).append(Math.sqrt(i)); than this, as it performs no
return buf.stoString(); synchronization.
}
If no initial value in the constructor, an initial capacity is 16.
If we set enough in the constructor, it would be more
effective.
Java Programming 20