[英]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.