[英]How to properly iterate over two loops
我想将我的字符串替换为其他字符串但没有很多符号。 例如,我有“我想成为。#$%@,_”,它应该返回“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.
您可以像这样修复您的方法:
public static List<Character> count (String str){
char[] chars = str.toCharArray();
List<Character> charsWithOutSpecial = new ArrayList<>();
char[] specialChars = {' ','!','"','#','$','%','&','(',')','*','+',',',
'-','.','/',':',';','<','=','>','?','@','[',']','^','_',
'`','{','|','}','~','\\','\''};
for (int i = 0; i < chars.length; i++) {
boolean isCharValid = true;
// iterating over the special chars
for (int j = 0; j < specialChars.length; j++) {
if(specialChars[j] == chars[i]){
// we identified the char as special
isCharValid = false;
}
}
if(isCharValid){
charsWithOutSpecial.add(chars[i]);
}
}
return charsWithOutSpecial;
}
您想要的正则表达式可能是 [^a-zA-Z]
但是你也可以使用两个循环来做到这一点
StringBuilder str2 = new StringBuilder();
for (int j = 0; j < chars.length; j++) {
boolean special = false;
for (int i = 0; i < specialChars.length; i++) {
if(specialChars[i] == chars[j]){
special = true;
break;
}
}
if (!special) str2.append(chars[j]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.