java - 如何简化 split() 的实现?
问题描述
需要帮助简化 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);
解决方案
我从头开始做了一个新的拆分实现,至少在我看来(主观)是“更容易”理解的。你可能会也可能不会觉得它有用。
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 对您的学生来说太复杂,您可以将其替换为普通的字符串连接(效率较低且不好的做法)。
推荐阅读
- r - 当 API 调用在 Shiny 中返回空时显示错误消息?
- jquery - 在表内显示 ajax jquery 响应
- acceleo - 当我按照 wiki 中的 Acceleo 入门指南从 uml 生成 java 代码时出现问题
- c# - NReco.PdfGenerator.WkHtmlToPdfException:退出代码:-1073741521
- ios - 使用带有径向渐变的 CAGradientLayer 时出现奇怪的渐变。
- angular - angular 6 自定义元素指令
- html - 悬停时下拉菜单消失在滑块后面
- c# - Web Api,在响应中写入标头
- mongodb - 如何计算数组对象的大小并在 MongoDB 中展开
- shell - shell如何执行这段代码'cd $dir && php -f test_loop.php &'