java - 如何正确迭代两个循环
问题描述
我想将我的字符串替换为其他字符串但没有很多符号。例如,我有“我想成为!#$%@!_”,它应该返回“Iwanttobe”。这以某种方式起作用,但不幸的是它迭代了第一个循环(第一个字符),然后迭代了整个第二个循环。我希望它遍历所有第一个,然后遍历所有第二个,并基于此将字符添加到我的新表中
这是我的方法:
public static List<Character> count (String str){
char[] chars = str.toCharArray();
List<Character> charsWithOutSpecial = new ArrayList<>();
char[] specialChars = {' ','!','"','#','$','%','&','(',')','*','+',',',
'-','.','/',':',';','<','=','>','?','@','[',']','^','_',
'`','{','|','}','~','\\','\''};
for (int i = 0; i < specialChars.length; i++) {
for (int j = 0; j < chars.length; j++) {
if(specialChars[i] != chars[j]){
charsWithOutSpecial.add(chars[j]);
}
}
}
return charsWithOutSpecial;
}
解决方案
这应该做的工作:
str = str.replaceAll("[^A-Za-z0-9]", ""); // replace all characters that are not numbers or characters with an empty string.
推荐阅读
- c++ - char 数组的操作如何导致堆栈溢出?
- angular - 循环依赖中带有警告的角度路由服务
- html - CSS 动画结束后显示 Div
- pytorch - 如何在 HPC 中使用 DistributedDataParallel() 和 init_process_group()?
- java - Jython 未加载 fxml 文件
- python - 在python中异步同一函数的多个实例
- postgresql - 致命错误。无法联系应用服务器
- scala - 收集信息与行联合的 Apache Spark 列
- r - 在R中逐行替换数据框中的值
- reactjs - Redux reducer:在返回新状态时将对象添加到数组