My split function in Java

来源:互联网 发布:python八数码算法 编辑:程序博客网 时间:2024/06/05 04:26

This program aims for split an input string by specified characters, like ',' ' ' and so on.

import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class MyTokenClass {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubMyTokenClass mytoken = new MyTokenClass();String str = "a, b, c, da, dc, m#";str = mytoken.getInput();List<String> strList = mytoken.myTokenMethod(str, ',');for(String strObj:strList){System.out.print(strObj+" ");}mytoken.sortList(strList);}public String getInput() throws IOException{InputStreamReader r = new InputStreamReader(System.in);int c;c= r.read();StringBuffer inputStr = new StringBuffer("");while(c != '#' && c != -1){inputStr.append((char)c);c= r.read();}return inputStr.toString();}public List<String> myTokenMethod(String str, char splitChar){List<String> strList = new ArrayList<String>();int length = str.length();int startIndex = 0;int endIndex = 0;for(int i = 0; i < length; ++i){if(str.charAt(i) == splitChar){if(i == 0){endIndex = startIndex = i+1;}else{endIndex = i-1;}if(str.substring(startIndex, endIndex+1).replaceAll(" ", "").equals("") == false)strList.add(str.substring(startIndex, endIndex+1).replaceAll(" ", ""));startIndex = i+1;}else{endIndex++;}}strList.add(str.substring(startIndex, endIndex+1).replaceAll(" ", ""));return strList;}public void sortList(List<String> strList){System.out.println("\nAfter sorting("+strList.size()+"):");Collections.sort(strList);for(String std:strList){System.out.println(std);}}}


代码运行结果:


0 0
原创粉丝点击