java - 不使用 split() 拆分单词
问题描述
我设法用某个符号分割给定的单词或句子,现在我想知道是否可以将多个符号作为字符串来做到这一点。例如,如果我有 ("1+1=2"),并尝试将其拆分为 ("+=")?
我考虑过将 symbol 声明为字符串,然后将我已经拥有的循环放在另一个循环中,以便为 symbol 中的每个字符测试 word 中的任何字符,但老实说,这让我感到困惑。
^-^ 我很感谢任何建议。
公共静态无效 splitBySymbol() {
int i = 0;
while (i < word.length()) {
if (word.charAt(i) == symbol) {
System.out.println( word.substring(0,i)); ;
word = word.substring(i + 1);
i = -1;
}
i++;
}
}
解决方案
如果您只想打印零件,您可以:
public static void splitBySymbol(String word, String symbols)
{
// Check each char
for (int i = 0; i < word.length(); i++) {
// Get the current char and convert to string (for contains())
String c = Character.toString(word.charAt(i));
// If it is a delimeter, print a new line
if (symbols.contains(c)) {
System.out.println();
}
// Otherwise, print the char
else {
System.out.print(c);
}
}
}
推荐阅读
- python - localhost 拒绝在调用 google api 的 databricks 笔记本中连接
- sql - 无法编辑查询中的字段
- kdb - kdb:过滤表匹配符号列:~ vs =
- google-apps-script - Google Workspace Add On HomepageTrigger 在更改标签时在 Google 表格中触发?
- python - Python 3.9.1 pip install python-binance win32 visualstudio
- r - 如何将散点添加到箱形图中
- c++ - 使用迭代器实现stl向量构造函数
- javascript - reactJS中实现加密解密OpenSSL和zlib
- node.js - Node fs rmdir TypeError '回调必须是一个函数'
- android - Android:另一个AlertDialog动作中的AlertDialog