Java 字串分開的方法

用split
 
String test = "It's a dog.";
String[] testSplit = test.split(" "); 
for ( int i = 0 ; i < testSplit.length ; i++ ){ 
     System.out.println(testSplit[i]);
     System.out.println("\n");
} 
 
印出
It's
a
dog.
 
###################################################################
用token
 
String ori1 = "I am a good man.";
StringTokenizer st1 = new StringTokenizer(ori1);
while (st1.hasMoreTokens()) {
         System.out.print(st1.nextToken());
         System.out.print('\n')
} 

印出
I
am
good
man


####################################################################
用 scaner
String ori1 = "I am a good man.";
Scanner tokenize = new Scanner(ori1);
while (tokenize.hasNext()){
  System.out.print(tokenize.next());
  System.out.print("\n");
}
 
印出
I
am
good
man

除了split可以任意指定要分隔的字元。
token 和 scanner 都只能分隔空白鍵。





留言

這個網誌中的熱門文章

python 找圖自動點擊

Python pyserial 抓取系統內的 COM PORT

VBA EXCEL 工作表變化 馬上執行 的作法 Worksheet_Change