Download String

Document related concepts
no text concepts found
Transcript
http://www.csie.nctu.edu.tw/~tsaiwn/oop/
Programming in Java
String and String Parser
java.util.* -- Vector, Stack, HashTable…
蔡文能
交通大學資訊工程學系
[email protected]
交通大學資訊工程學系
Java
String and Parser
Agenda
Character, String class and the StringBuffer
class
Character in a String -- charAt(int i)
SubString in a String – substring(int p, int n)
More String/StringBuffer methods
Type Wrappers again
Utilities -- java.util.*
 StringTokenizer
 Vector, Stack, HashTable
交通大學資訊工程學系 蔡文能
第2頁
Java
String and Parser
Consider how to read a number?
In C Language:
 scanf with %d format (%f for float, %lf for double)
May cause program down due to strange input
May forget to pass address of variable to scanf
 Better way
Read it into program as a string ( how ? )
 gets(buf); /* not good enough */
 fgets(buf, sizeof(buf), stdin); /* buf is a char array */
Then, use sscanf to scan that string; or use the following utility
functions:
 atol, atof, strtol, strtod, strtok, strsep
What about in Java ?
交通大學資訊工程學系 蔡文能
第3頁
Java
String and Parser
String in Java is not char array
String is not a char array in Java
String is different from StringBuffer
Elements in String/StringBuffer can be accessed
via using the charAt( position ) method.
The content of a String can not be modified
substring ?
capacity of a StringBuffer ? Size of a String
Buffer ?
 size <= capacity
交通大學資訊工程學系 蔡文能
第4頁
Java
String and Parser
Characters
In Java single characters are represented using the data type
char. ( do NOT confuse with the wrapper Character class)
 char is one of the 8 primitive data types.
 Character constants are written as symbols enclosed in single quotes,
for example, 'a', 'X', and '5'. ( ' : apostrophe, " : quote )
To represent characters in computer, U. S. computer
manufacturers devised several coding schemes.
One coding scheme widely used today is ASCII (American
Standard Code for Information Interchange).
To accommodate the character symbols of non-English
languages, the Unicode Consortium established the Unicode
Worldwide Character Standard, commonly known as Unicode
=> http://www.unicode.org/
交通大學資訊工程學系 蔡文能
第5頁
Java
String and Parser
Strings
Not String
Features:




Strings are objects and java.lang.String is the class.
Use 16 bit UNICODE
All objects (java.lang.Object) have methods toString();
Special treatment of the + operator
"Object" + obj + "will call toString( ) function"

new StringBuffer("Object").append(obj.toString())
.append("will call toString( ) function").toString()
Example:
System.out.println("Hello World");
String hey = "Hello";
String you = "World";
System.out.println(hey + " " + you);
int len = hey.length();
Notice the performance.
交通大學資訊工程學系 蔡文能
第6頁
Java
String and Parser
StringBuffer
For the StringBuffer Class
 StringBuffer provides length and charAt accessor
methods, as well as the String class.
 capacity method
Returning the amount of space currently allocated for the
StringBuffer, rather than the amount of space used.
For example, in reverseIt method (next page) :
 dest.capacity() will never change.
 dest.length() will increase for each iteration.
 Initializing a StringBuffer's capacity to a reasonable first
guess.
Minimizing the number of times memory must be allocated for it.
交通大學資訊工程學系 蔡文能
第7頁
Java
String and Parser
String vs. StringBuffer
Use the String class when you are working with strings
that cannot change.
StringBuffer is used when you want to manipulate the
contents of the string on the fly.
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
交通大學資訊工程學系 蔡文能
第8頁
Java
String and Parser
Creating Strings and StringBuffers
Creating a String
 String a = "Gobbledy gook.”;
 new String("Gobbledy gook.");
Creating a StringBuffer
 StringBuffer dest = new StringBuffer(len);
 StringBuffer's default constructor may leaves the buffer's
length undetermined.
 It's more efficient to specify the length of the buffer.
交通大學資訊工程學系 蔡文能
第9頁
Java
交通大學資訊工程學系 蔡文能
String and Parser
第10頁
Java
String and Parser
String and StringBuffer are Objects
String is a class in the java.lang package.
Because String is a class, we need to create an instance of String in Java for
string processing. Like any other objects,
we need a declaration and object creation for the instances of the String class.
For example,
String name1;
name1 = new String( "Latte" );
But we normally use a shorthand, instead, treating
String objects much like primitive data. For example,
These two
statements
are
equivalent.
String name1;
name1 = "Latte";
交通大學資訊工程學系 蔡文能
第11頁
Java
String and Parser
Accessing char Elements in a String
Individual characters in a String accessed with the charAt method.
char charAt(int index)
 Returns the character at the
specified index.
 An index ranges from 0 to length( ) - 1.
 The first character of the sequence
is at index 0, the next at index 1,
and so on, as for array indexing.
不可以直接使用 s[n] 而要改用 s.charAt(n)
交通大學資訊工程學系 蔡文能
第12頁
Java
String and Parser
Accessing char Elements in a String (cont.)
String name = "Example";
0
1
2
3
4
5
6
E
x
a
m
p
l
e
name
This variable refers to the
whole string.
交通大學資訊工程學系 蔡文能
name.charAt( 3 )
The method returns the
character at position # 3.
第13頁
Java
String and Parser
substring in a String/StringBuffer
substring in a String accessed with the substring method.
String substring(int beginIndex)
 Returns a new string that is a substring of this
string. The substring begins with the character
at the specified beginIndex and extends to the end
of this string.
Examples: "unhappy".
 substring(2) returns "happy"
 substring(3) returns “appy"
String substring(int beginIndex, int endIndex)
 Returns a new string that is a substring of this
string. The substring begins at the specified
beginIndex and extends to the character at index
endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Examples: "hamburger".
 substring(4, 8) returns "urge"
"smiles".
 substring(1, 5) returns "mile"
交通大學資訊工程學系 蔡文能
第14頁
Java
String and Parser
Determining the String Size
We determine the number of characters in a String with the length
method.
String name = “Sumatra”,
str1 = “one”,
str2 = “”,
str3;
name.length( );
7
Error because
no object is
created for str3,
so it is a null.
str1.length( );
3
str2.length( );
0
str3.length( );
Error!
交通大學資訊工程學系 蔡文能
第15頁
Java
String and Parser
Example using length( ) , charAt(int i)
Reverse a string
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
交通大學資訊工程學系 蔡文能
第16頁
Java
String and Parser
More String/StringBuffer Methods
int indexOf(int character)
int lastIndexOf(int character)
 Return the index of the first (last) occurrence of the specified
character.
int indexOf(int character, int from)
int lastIndexOf(int character, int from)
 Return the index of the first (last) occurrence of the specified
character, searching forward (backward) from the specified
index.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
 Copies characters from this string into the destination character array.
boolean equals(Object anObject)
 Compares this string to the specified object.
Object clone() throws CloneNotSupportedException
 Creates and returns a copy of this object.
交通大學資訊工程學系 蔡文能
第17頁
Java
String and Parser
String Concatenation
Concatenation and the + Operator
 In Java, you can use + to concatenate String:
String cat = "cat";
System.out.println("con" + cat + "enation");
 But the compiler uses StringBuffer to implement
concatenation behind the scenes.
String cat = "cat";
System.out.println(new StringBuffer().append("con").
append(cat).append("enation").toString());
交通大學資訊工程學系 蔡文能
第18頁
Java
String and Parser
Converting Objects to Strings
The toString Method
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
All classes inherit toString from the Object class.
 Many classes in the java.lang package override this method to provide
an implementation that is meaningful to that class.
The valueOf Method
 You can use valueOf to convert variables of different types to String.
System.out.println(String.valueOf(Math.PI));
交通大學資訊工程學系 蔡文能
第19頁
Java
String and Parser
Converting Strings to Numbers
The "type wrapper" classes (Integer, Long, Float,
and Double) provide a class method named valueOf
that converts a String to an object of that type.
String piStr = "3.14159";
Float pi = Float.valueOf(piStr); /*物件*/
float pi2 = Float.parseFLOAT(piStr); /*值*/
Object
class method = static method
交通大學資訊工程學系 蔡文能
第20頁
Java
String and Parser
TYPE Wrapper Long (1/2)
As we mentioned before, every Primitive data type has
corresponding type wrapper.
Long
 Field Summary
static long MAX_VALUE = The largest value of type long.
static long MIN_VALUE = The smallest value of type long.
static ClassTYPE = The Class object representing the primitive type long.
 Constructor Summary
Long(long value) : Constructs a newly allocated Long object that represents the
primitive long argument.
Long(String s) :
Constructs a newly allocated Long object that
represents the value represented by the string in decimal form.
交通大學資訊工程學系 蔡文能
第21頁
Java
String and Parser
TYPE Wrapper Long (2/2)
some methods of the class Long
 static String toHexString(long i)
Creates a string representation of the long argument as an unsigned
integer in base 16.
 static String toOctalString(long i)
Creates a string representation of the long argument as an unsigned
integer in base 8.
 static long parseLong(String s)
Parses the string argument as a signed decimal long.
 static long parseLong(String s, int radix)
Parses the string argument as a signed long in the radix specified by
the second argument.
 static long valueOf(String s)
Returns a new long object initialized to the value of the specified
String.
交通大學資訊工程學系 蔡文能
第22頁
Java
String and Parser
Strings and the Java Compiler
Literal Strings
 You can use literal strings anywhere you would use a String object.
System.out.println("Hello World!");
 You can also use String methods directly from a literal string.
int len = "Goodbye Cruel World".length();
 These two constructs are equivalent.
String s = "Hala Hala";
String s = new String("Hala Hala");
But first one which is more efficient than the second.
The second end up creating two String objects instead of one.
交通大學資訊工程學系 蔡文能
第23頁
Java
String and Parser
More about I/O : C
Read an Integer
C
static char buf[999];
fgets(buf, sizeof(buf), stdin); /* read one line first */
static char buf[999];
file * fp; int haha;
fp = fopen("myinput.dat", "rt");
fgets(buf, sizeof(buf), fp); /* read one line first */
haha = atol(buf);
交通大學資訊工程學系 蔡文能
第24頁
Java
String and Parser
More about I/O : C++
Read an Integer
C++
static char buf[999];
cin.getline(buf, sizeof(buf) ); /* read one line first */
static char buf[999];
fstream fs; int haha;
fs.open( "myinput.dat", ios::in);
fs.getline(buf, sizeof(buf) ); /* read one line first */
int haha = atol(buf);
交通大學資訊工程學系 蔡文能
第25頁
Java
String and Parser
More about I/O : Java
Read an Integer
Java
Use BufferedReader
 Stream 要先轉為 Reader: InputStreamReader
 把Reader 丟給BufferedReader 包起來
Use readLine( ) in BufferedReader
Use ???.parse??? ( Double.parseDouble( yourString ) );
 i.e., methods in class wrapper
Use StringTokenizer
 To parse string contains several tokens
交通大學資訊工程學系 蔡文能
第26頁
Java
String and Parser
Example: using BufferedReader
InputStreamReader isr = new InputStreamReader(System.in);
/* 鍵盤是以 byte 為單位的 Stream */
BufferedReader br = new BufferedReader(isr);
/* BufferedReader 的 constructor 只接受 Reader */
/* 所以不能直接把 System.in 丟給它 */
String stmp = br.readLine( ); /* 讀入一整列 */
long x = Long.parseLong(stmp); /* if it is a long */
/* 使用 class wrapper */
double x = Double.parseDouble(stmp); /* if double */
一列有多項輸入則可使用 StringTokenizer
交通大學資訊工程學系 蔡文能
第27頁
Java
String and Parser
Utilities ( java.util.* )
In java.util.*,





StringTokenizer
Vector
Hashtable
Properties
...
Vector is a growable array of objects.
In Hashtable, an entry has two parts: a name and a value.
 Pairs of name/value are objects.
 Use hashing to find each pair.
 Also known as associative array, or called “map”.
In Properties, inherits from Hashtable.
 Pairs of name/value are Strings.
交通大學資訊工程學系 蔡文能
第28頁
Java
交通大學資訊工程學系 蔡文能
String and Parser
第29頁
Java
交通大學資訊工程學系 蔡文能
String and Parser
第30頁
Java
String and Parser
StringTokenizer (1/3)
交通大學資訊工程學系 蔡文能
第31頁
Java
String and Parser
StringTokenizer (2/3)
import java.io.*;
import java.util.*;
public class Test {
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(isr);
public static void main ( String p[ ] ) throws Exception { new Test( ); }
Test( ) throws Exception {
System.out.print("In: "); String x = b.readLine();
System.out.println("Got "+ x);
StringTokenizer s = new StringTokenizer(x, " ,\t" );
while(s.hasMoreTokens( ) ){
System.out.println(s.nextToken( ));
}
System.out.println("======");
}
}
交通大學資訊工程學系 蔡文能
第32頁
Java
StringTokenizer (3/3) String and Parser
System.out.print("\r\nYour 三圍, 空白或逗號隔開: ");
String tmps = b.readLine();
StringTokenizer s = new StringTokenizer(tmps, " ,\t");
int kk=0; round[2] = round[1] = round[0] =0;
try{ while(s.hasMoreTokens () ) {
round[ kk++ ] = Double.parseDouble( s.nextToken() );
if(kk > 3 ) break;
}
} catch (Exception e)
{ System.out.println("Missing "+ (4-kk) + " round"); kk=3;}
if(kk < 3 ) { System.out.println("Missing "+ (3-kk) + " round");}
System.out.println("===Thank you!===");
PrintStream myoo = System.out;
myoo.println("\r\n=== Your Name is " + name);
myoo.println("Height = " + height + " \t" + "Weight = " + wet);
myoo.print("Three circle(三圍)== "); DecimalFormat dd = new
DecimalFormat("####0.00"); myoo.print( dd.format( round[0] ) );
myoo.print( " , " + dd.format( round[1] ) +" , "+ dd.format(round[2]) );
myoo.println("\r\n====== ====== ======");
交通大學資訊工程學系 蔡文能
第33頁
Java
String and Parser
Vectors (1/5)
This class is in the java.util package
You make it available to your program with import
statement “import java.util.Vector” or “import java.util.*”
at the top of your program.
Intended for dynamic sizes of elements.
 Lets you add arbitrary objects to a list of objects
 E.g., addElement(x);
Reallocate the internal array when grows doubly (or a
constant factor).
交通大學資訊工程學系 蔡文能
第34頁
Java
String and Parser
Vectors (2/5)
Performance: flexible and efficient
 Access time complexity: O(1)
 Time complexity for addElement(x):
Amortized for access: O(1)
Times of calling malloc(): O((log n)/n)
 Memory complexity: No more than 2 or constant times more.
 But,
Not efficient for removeElement().
Not so efficient because it uses synchronized.
 Sun internally uses a class named FastVector, without
synchronized.
Similarly, for StringBuffer and Hashtable.
 Note: for String, don’t concatenate strings in a loop!
交通大學資訊工程學系 蔡文能
第35頁
Java
String and Parser
Vectors (3/5)
交通大學資訊工程學系 蔡文能
第36頁
Java
交通大學資訊工程學系 蔡文能
String and Parser
Vectors (4/5)
第37頁
Java
String and Parser
Vectors (5/5)
java.util.Vector
java.lang.Object
|
+ - - java.util.AbstractCollection
|
+ - - java.util.AbstractList
|
+ - - java.util.Vector
Direct Known Subclasses:
Stack
交通大學資訊工程學系 蔡文能
第38頁
Java
String and Parser
Stack
交通大學資訊工程學系 蔡文能
第39頁
Java
String and Parser
javap java.util.Stack
交通大學資訊工程學系 蔡文能
第40頁
Java
String and Parser
java.util.AbstractList
交通大學資訊工程學系 蔡文能
第41頁
Java
String and Parser
java.util.LinkedList
交通大學資訊工程學系 蔡文能
第42頁
Java
String and Parser
Interface Queue
java.util
Interface Queue <E>
Type Parameters:
 E - the type of elements held in this collection
Since:
 JDK 1.5
交通大學資訊工程學系 蔡文能
第43頁
Java
String and Parser
Hashtable (1/3)
Implements a hashtable in Java
Hashtables have keys and values
Key
“Joe”
“Fred”
“Heather”
交通大學資訊工程學系 蔡文能
Value
employee object
employee object
employee object
第44頁
Java
String and Parser
Hashtable (2/3)
交通大學資訊工程學系 蔡文能
第45頁
Java
String and Parser
Hashtable (3/3)
A hashtable can be used to quickly look up an object
associated with a key.
The key uses the hashcode() method for fast access
get() and put() are used to add and remove objects from the
table
elements() returns an object that lets you cycle through the
hashtable
Also take a look at HashMap
(The HashMap class is roughly equivalent to Hashtable, except
that it is unsynchronized and permits nulls.)
交通大學資訊工程學系 蔡文能
第46頁
Java
String and Parser
Properties
交通大學資訊工程學系 蔡文能
第47頁
Java
String and Parser
Properties
The Properties class itself provides methods for the following:





Loading key/value pairs into a Property object from a stream
Retrieving a value from its key
Listing the keys and their values
Enumerating over the keys
Saving the properties to a stream
Properties extends the Hashtable class:







Testing to see if a particular key or value is in the Properties object.
Getting the current number of key/value pairs.
Removing a key and its value.
Adding a key/value pair to the Properties list.
Enumerating over the values or the keys.
Retrieving a value by its key.
Finding out if the Properties object is empty.
Important to be used as something like configuration files or *.ini files.
交通大學資訊工程學系 蔡文能
第48頁
Java
String and Parser
The Life Cycle of Program's Properties
交通大學資訊工程學系 蔡文能
第49頁
Java
String and Parser
Loading from FileInputStream
Setting Up Your Properties Object
 loading the default properties and loading the remembered
properties:
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new
FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create program properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
交通大學資訊工程學系 蔡文能
第50頁
Java
String and Parser
Saving to FileOutputStream
 The following example writes out the application
properties from the previous example using Properties's
save method. The default properties don't need to be
saved each time because they never change.
FileOutputStream out =
new FileOutputStream("appProperties");
applicationProps.save(out, "---No Comment---");
out.close();
交通大學資訊工程學系 蔡文能
第51頁
Java
String and Parser
Properties Methods (1/2)
 getProperty(String key)
 getProperty(String key,String default)
Returns the value for the specified property. The second version allows you to
provide a default value. If the key is not found, the default is returned.
 list(PrintStream s)
 list(PrintWriter w)
Writes all of the properties to the specified stream or writer. This is useful for
debugging.
 elements()
 keys()
 propertyNames()
Returns an Enumeration containing the keys or values (as indicated by the
method name) contained in the Properties object.
 size()
Returns the current number of key/value pairs.
交通大學資訊工程學系 蔡文能
第52頁
Java
String and Parser
Properties Methods (2/2)
 contains(Object value)
 containsKey(Object key)
Returns true if the value or the key is in the Properties object.
Properties inherits these methods from Hashtable. Thus they
accept Object arguments. You should pass in Strings.
 put(Object key, Object value)
Puts the key/value pair in the Properties object.
 remove(Object key)
Removes the key/value pair associated with key.
Both put and remove come from Hashtable and thus take
Objects.
交通大學資訊工程學系 蔡文能
第53頁
Java
String and Parser
Properties File Format
Each of the following lines specifies:
 Key: "Truth"; Value: "Beauty".
Truth = Beauty
Truth:Beauty
Truth
:Beauty
The following three lines specify a single property:
fruits
apple, banana, pear, \
cantaloupe, watermelon, \
kiwi, mango
The empty string:
cheese
交通大學資訊工程學系 蔡文能
第54頁
Java
String and Parser
Using Properties to Manage
Program Attributes
An attribute has two parts: a name and a value.
For example
 "os.name" is the name for one of the Java platform's system attributes.
 Its value contains the name of the current operating system, such as
“Linux".
Many subsystems use properties files to set default properties. E.g.,





System
Resource bundling
Security manager
Servlet
JSP
交通大學資訊工程學系 蔡文能
第55頁
Java
String and Parser
Introduction to Java Programming
謝謝捧場
http://www.csie.nctu.edu.tw/~tsaiwn/oop/
蔡文能
交通大學資訊工程學系 蔡文能
第56頁