我正在创建一个循环,它将测试用户输入的每个子字符串以测试非法字符。但是,它仅检测非法字符何时位于输入的最后位置。我觉得解决方案可能很简单,但我似乎无法弄清楚,我该如何纠正这个问题,以便它可以在字符串中的任何位置检测到它?
public class IllegalFileName {
public static final Set<String> illegalCharsSet = new HashSet<String>(
Arrays.asList("/", "\n", "\r", "\t", "\0", "\f", "`", "?", "*",
"\\", "<", ">", "|", "\"", ":", ".", "£", "$", "%", "^",
"&", ")", "("));
public static void main(String[] args) {
String illegalNameText = "££!233";
String illegalNameText2 = "££!233$";
boolean illegalName = false;
for (int i = 0; i <= illegalNameText.length() - 1; i++) {
System.out.println(i);
if (illegalCharsSet.contains(illegalNameText.substring(i))) {
System.out.println(illegalNameText + " is illegal");
illegalName = true;
System.out.println(illegalNameText.substring(i));
}
}
for (int i = 0; i <= illegalNameText2.length() - 1; i++) {
System.out.println(i);
if (illegalCharsSet.contains(illegalNameText2.substring(i))) {
System.out.println(illegalNameText2 + " is illegal");
illegalName = true;
System.out.println(illegalNameText2.substring(i));
}
}
}
}