import java.util.StringTokenizer;
public class SplitDemo {
//jdk8
public static void main(String[] args){
String s = "a,b,c";
String[] split = s.split(",");
for (String s1 : split) {
System.out.println(s1);
}
StringTokenizer st = new StringTokenizer(s,",");
while (st.hasMoreTokens()){
String s1 = st.nextToken();
System.out.println(s1);
}
String s2 = "a,b,c";
while (true){
int i = s2.indexOf(",");
if (i < 0 && s2.length()<0){
break;
}
if (i < 0){
System.out.println(s2);
break;
}else {
System.out.println(s2.substring(0,i));
s2 = s2.substring(i+1);
}
}
testSplit();
testStringTokenizer();
testIndexOf();
//split-598
//StringTokenizer-38
//indexOf-4577
}
public static void testSplit(){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sb.append(i);
if (i < 999){
sb.append(",");
}
}
String str = sb.toString();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
str.split(",");
}
long end = System.currentTimeMillis();
System.out.println("split" + (end-begin));
}
public static void testStringTokenizer(){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sb.append(i);
if (i < 999){
sb.append(",");
}
}
String str = sb.toString();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()){
st.nextToken();
}
st = new StringTokenizer(str);
}
long end = System.currentTimeMillis();
System.out.println("StringTokenizer" + (end-begin));
}
public static void testIndexOf(){
String s = null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sb.append(i);
if (i < 999){
sb.append(",");
}
}
s = sb.toString();
String str = s;
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
while (true){
int a = str.indexOf(",");
if (a < 0){
break;
}
str = str.substring(a+1);
}
str = s;
}
long end = System.currentTimeMillis();
System.out.println("indexOf" + (end-begin));
}
}