给定一个字符串str ,任务是从中删除所有非字母数字字符并打印修改后的字符。
例子:
Input: @!Geeks-for’Geeks,123
Output: GeeksforGeeks123
Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes(‘), and commas(, ) are removed.
Input: Geeks_for$ Geeks?{}[]
Output: GeeksforGeeks
Explanation: underscore(_), dollar sign($), white space, question mark(?), curly braces({}), and square bracket([]) are removed.
Input: GeeksforGeeks123
Output: GeeksforGeeks123
Explanation: No need to remove any character, because the given string doesn’t have any non-alphanumeric character.
方法 1:使用 ASCII 值
由于字母数字字符位于大写字母的 [65, 90]、小写字母的 [97, 122] 和数字的 [48, 57] 的 ASCII 值范围内。因此遍历由字符字符串字符和提取每个字符的ASCII值。如果 ASCII 值不在上述三个范围内,则该字符为非字母数字字符。因此跳过这些字符并将其余字符添加到另一个字符串并打印它。
方法 2:使用 String.replaceAll()
非字母数字字符包括除字母和数字之外的所有字符。它可以是标点符号字符,如感叹号,at符号(@),逗号(,),问号,冒号(:),破折号((!)(?) – )等,以及特殊字符,如美元符号($),等于符号(=) ,加号(+) ,撇号(‘) 。
方法是使用 String.replaceAll 方法将所有非字母数字字符替换为空字符串。
下面是上述方法的实现:
Java
// Java program to remove non-alphanumeric
// characters from a string
class GFG {
// Function to remove non-alphanumeric
// characters from string
public static String
removeNonAlphanumeric(String str)
{
// replace the given string
// with empty string
// except the pattern "[^a-zA-Z0-9]"
str = str.replaceAll(
"[^a-zA-Z0-9]", "");
// return string
return str;
}
// Driver Code
public static void main(String args[])
{
// Test Case 1:
String str1
= "@!Geeks-for'Geeks, 123";
System.out.println(
removeNonAlphanumeric(str1));
// Test Case 2:
String str2
= "Geeks_for$ Geeks?{}[]";
System.out.println(
removeNonAlphanumeric(str2));
// Test Case 3:
String str3
= "GeeksforGeeks123";
System.out.println(
removeNonAlphanumeric(str3));
}
}
GeeksforGeeks123
GeeksforGeeks
GeeksforGeeks123
方法三:使用正则表达式
另一种方法涉及使用正则表达式。可以使用 ReGex [^a-zA-Z0-9 ]轻松过滤字符串。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live