3 回答

TA貢獻1848條經驗 獲得超10個贊
您的問題說您不想使用正則表達式,但我認為沒有理由要求該要求,除了這可能是家庭作業(yè)。如果您愿意在此處使用正則表達式,那么有一個單行解決方案可將您的輸入字符串拆分為以下模式:
(?<=\S)(?=\s)|(?<=\s)(?=\S)
這種模式使用環(huán)視來分割,無論前面是非空白字符,后面是空白字符,反之亦然。
String input = "EE B";
String[] parts = input.split("(?<=\\S)(?=\\s)|(?<=\\s)(?=\\S)");
System.out.println(Arrays.toString(parts));
[EE, , B]
^^ a single space character in the middle

TA貢獻1872條經驗 獲得超4個贊
如果我理解正確,您希望將字符串中的字符分開,以便類似連續(xù)的字符保持在一起。如果是這種情況,我會這樣做:
public static ArrayList<String> splitString(String str)
{
ArrayList<String> output = new ArrayList<>();
String combo = "";
//iterates through all the characters in the input
for(char c: str.toCharArray()) {
//check if the current char is equal to the last added char
if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {
output.add(combo);
combo = "";
}
combo += c;
}
output.add(combo); //adds the last character
return output;
}
請注意,我沒有使用數(shù)組(具有固定大?。﹣泶鎯敵?,而是使用了ArrayList具有可變大小的 。此外,與其檢查下一個字符是否與當前字符相等,我更喜歡使用最后一個字符。該變量combo用于在字符轉到 之前臨時存儲它們output。
現(xiàn)在,這是按照您的指南打印結果的一種方法:
public static void main(String[] args)
{
String input = "EEEE BCD DdA";
ArrayList<String> output = splitString(input);
System.out.print("[");
for(int i = 0; i < output.size(); i++) {
System.out.print("\"" + output.get(i) + "\"");
if(i != output.size()-1)
System.out.print(", ");
}
System.out.println("]");
}
運行上述代碼時的輸出將是:
["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]
添加回答
舉報