java - 令牌 - 字符串 Java
问题描述
我成功完成了以下任务,但是代码效率非常低,如果有人可以向我展示一种更有效的方法,我将不胜感激,也许是子字符串。那作业:
/**
* Separates a given string into tokens, which are the "words" that are
* separated by one or more occurrences of the given separator character.
* Returns the tokens as an array of String values.
*/
public static String[] tokenize (String str, char separator) {
// Removes all the occurrences of the separator at the beginning and end of str
String source = trim(str, separator);
String[] tokens = new String[charRunCount (source,separator)+1];
String tmp = ""; // a string in order to take a word, then run over this string
int j = 0;
int i = 0;
while (i < tokens.length) {
if ( source.charAt (j) != separator ) {
do {
tmp += source.charAt (j);
if ( j >= source.length () - 1 ) {
break;
}
else { // so that we math the source length
j++;
}
} while (source.charAt (j) != separator);
}
if ( source.charAt (j) == separator ) {
j++;
while (source.charAt (j) == separator) {
j++;
}
}
tokens[i] = tmp;// taking the token into place
tmp = ""; //resetting the token so we can begin anew
i++;
}
return tokens;
}
cahrRunCount 函数:
public static int charRunCount(String str, char c){
char last = 0;
int counter = 0;
for (int i = 0; i < str.length(); i++) {
// whenever a run starts.
if (last != c && str.charAt(i) == c) {
counter++;
}
last = str.charAt(i);
}
return counter;
}
我不能使用导入或正则表达式,谢谢!
解决方案
使用 String.split 方法
String[] tokens = str.split(separator)
for(String token:tokens){
//your code goes here
}
文档在这里
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
推荐阅读
- flutter - 如何在 Flutter 中进行自定义边框设计?
- reactjs - “Reactjs”如何在不使用钩子的情况下在功能组件内创建模式
- r - 如何使用 r 中“下一个”组的第一个值?
- tensorflow - 为什么 Huggingface create_optimizer 方法不起作用?
- python - Selenium:等到元素中不存在文本
- reactjs - 在反应中映射项目列表并分别编辑每个项目
- matlab - 在matlab中找到biginteger的模幂
- python - 存储过程输出参数不变
- python-3.x - 无法分配“''”:“IncomeExpense.username”必须是“用户”实例
- javascript - PDFKIT 溢出数据转到每一行的新页面