Splitting text in Java

Report
SPLITTING TEXT IN JAVA
Shene J Jamal
Splitting a text
• Generally, there are two ways to split a string in Java
1- By using an object from StringTokenizer which belongs
to the package java.util.StringTokenizer.
2- By using the Split() methods which belongs to the Java
String class.
StringTokenizer
• Used to split a String into different tokens by a defined
delimiter. (space is the default delimiter)
String str = "This is String Tokenizer Example";
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
StringTokenizer
• A delimiter could also be defined
String str = "This is a String| Tokenizer| Example";
StringTokenizer st = new StringTokenizer(str, ”|”);
while (st.hasMoreElements()) {
System.out.println(st.nextElement()); }
• Tokenizer returns one token at a time
Using split methods
• There are two split methods Java String class.
• A split method returns an array of string.
String input = “Hello- we are- trying to split a text- using
Split methods";
String[]records = input.split(“-");
//OR String[]records = input.split(“-“, 2);
The second argument is the limit.
Lab Problem
• Split the content of a file and print the result
Ahmed:co12hp:200
Ali:co12dell:300
Suha:mo123lg:300
Huda:ca123sonny:2
00
Suzi:co234sam:800
• The file
• The output
Ahmed
Co12hp
200
Ali
Co12dell
300
Suha
Mo123lg
300
Huda
Ca123sonn
y
200

similar documents