我正在尝试在Java中创建一个方法,该方法将识别一行文本中的非字母数字符号并将其删除。但是,我可以使用的工具有限。我必须使用循环和扫描程序来读取文本,并且只使用charAt和substring方法来删除有问题的字符。这是我提出的代码
public String sanitize2(){
Scanner sanitizer = new Scanner(input.getText());
String toBeSanitized = sanitizer.nextLine();
int length = toBeSanitized.length();
for (int i=0;i < toBeSanitized.length(); i++){
if ((toBeSanitized.charAt(i) >= 'a' && toBeSanitized.charAt(i) <= 'z') ||
(toBeSanitized.charAt(i) >= 'A' && toBeSanitized.charAt(i) <= 'Z') ||
(toBeSanitized.charAt(i) >= '0' && toBeSanitized.charAt(i) <= '9'))
{
toBeSanitized = toBeSanitized.substring(0,i) + toBeSanitized.substring(i+1);
}
}
input.setText(toBeSanitized);
return toBeSanitized;
}
但是当我在输入字段中插入文本时,它完全给出了错误的答案。任何人都能明白我在这里做错了吗?
答案 0 :(得分:1)
如果您不需要使用所有给定的工具,那么我认为这可能有助于解决您的问题。
String toBeSanitized = "(*this*)* text is ^0nly for t3st!ng!";
String sanitizedStr = "";
int length = toBeSanitized.length();
for (int i=0;i < toBeSanitized.length(); i++){
if ((toBeSanitized.charAt(i) >= 'a' && toBeSanitized.charAt(i) <= 'z') ||
(toBeSanitized.charAt(i) >= 'A' && toBeSanitized.charAt(i) <= 'Z') ||
(toBeSanitized.charAt(i) >= '0' && toBeSanitized.charAt(i) <= '9') ||
toBeSanitized.charAt(i) == ' ') // optional
{
sanitizedStr += toBeSanitized.charAt(i);
}
}
System.out.println(sanitizedStr);
我还包括空格,但如果你愿意,可以删除它。 希望它有所帮助。