亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何簡化 split() 的實現?

如何簡化 split() 的實現?

智慧大石 2022-03-10 15:56:11
需要幫助簡化 split() 實現。不幸的是 split() 沒有包含在 AP JAVA 中。我需要向高中生展示,并且需要一種簡單易懂的方法。到目前為止,這是我想出的,但想知道我是否遺漏了一些明顯的東西。String[] tokens = new String[3]; boolean exit = false;do{    System.out.print( "Please enter first name, last name and password to logon or                       create a new account \n" + "use a space to seperate entries,                       no commas                                                  : ");   input = kboard.nextLine();   int spaces = 0;   if(input.length() == 0) exit = true;   if(!exit){                       //tokens = input.split(" ");       int idx;       int j = 0;       for (int i = 0; i < input.length();){           idx = input.indexOf(" ",i);           if(idx == -1 || j == 3) {               i = input.length();               tokens[j] = input.substring(i);           }else{                                       tokens[j] = input.substring(i,idx);                                      i = idx + 1;           }           j++;       }       spaces = j - 1 ;                   } // check we have 2 and no blank line     }while (spaces != 2 && exit == false); 
查看完整描述

1 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

我從頭開始做了一個新的拆分實現,至少在我看來(主觀)是“更容易”理解的。你可能會也可能不會覺得它有用。


public static String[] split(String input, char separator) {

    // Count separator (spaces) to determine array size.

    int arrSize = (int)input.chars().filter(c -> c == separator).count() + 1;

    String[] sArr = new String[arrSize];


    int i = 0;

    StringBuilder sb = new StringBuilder();

    for (char c : input.toCharArray()) { // Checks each char in string.

        if (c == separator) { // If c is sep, increase index.

            sArr[i] = sb.toString();

            sb.setLength(0); // Clears the buffer for the next word.

            i++;

        }

        else { // Else append char to current word.

            sb.append(c);

        }

    }

    sArr[i] = sb.toString(); // Add the last word (not covered in the loop).

    return sArr;

}

我假設您想使用原始數組進行教學,否則,我會返回一個 ArrayList 以進一步簡化。如果 StringBuilder 對您的學生來說太復雜,您可以將其替換為普通的字符串連接(效率較低且不好的做法)。


查看完整回答
反對 回復 2022-03-10
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號