给定字符串为str = "aQt4512m@!%n"
输出:
character:aQtmn , Number:4512 special:@!%
下面是代码,我试过了,但是,它是一个唯一的打印字符
String str = "asDftQ32$34h";
char[] chArr = str.toCharArray();
Character myChar = ' ';
for(int i=0;i<chArr.length;i++) {
myChar = ' ';
if(chArr[i]>=65 && chArr[i]<=122) {
myChar =chArr[i];
}
String tr = myChar.toString();
String dr = tr.replaceAll("\W","");
System.out.print(dr);
}
您可以像示例中那样使用replaceAll()来实现:
public class Main {
public static void main( String[] arg ) {
String str = "aQt4512m@!%n";
String chars = str.replaceAll( "[\W\d]", "" );
System.out.println( chars );
String special = str.replaceAll( "\w", "" );
System.out.println( special );
String numbers = str.replaceAll( "\D", "" );
System.out.println( numbers );
}
}
查看更多关于正则表达式的信息:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
代码如下:
- 处理文本字符串
- 沿途检查每个字符
c
- 如果
c
在a-z或a-z范围内,它将追加到名为"characters"> 的StringBuilder中。 - 如果在0-9的范围内,则附加在"数字"后面;
- 如果它在其他一些特殊字符的范围内,它会追加到"special">
- 如果在这些范围之外,它将打印一条消息以及字符
private static void separateCharacters(String str) {
StringBuilder characters = new StringBuilder();
StringBuilder digits = new StringBuilder();
StringBuilder special = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isAlphabetic(c)) {
characters.append(c);
} else if (Character.isDigit(c)) {
digits.append(c);
} else if ((c >= 33 && c <= 47) ||
(c >= 58 && c <= 64) ||
(c >= 91 && c <= 96) ||
(c >= 123 && c <= 126)) {
special.append(c);
} else {
System.out.println("skipping character: " + c);
}
}
System.out.println("characters : " + characters);
System.out.println("digits : " + digits);
System.out.println("special : " + special);
}
下面是输出"aQt4512m@!%n":
separateCharacters("aQt4512m@!%n");
characters : aQtmn
digits : 4512
special : @!%
再次,这次"aQt4512m@ ! % n(- =":
separateCharacters("azrRt07572m@!%n[-=");
characters : azrRtmn
digits : 07572
special : @!%[-=
我不喜欢"特别的"。处理,但这应该是一个足够的工作示例,以显示如何修改代码以包括/排除任何不同组的其他字符。或者,您可以选择遵循所有非字母、非数字字符都是"特殊"的逻辑,在这种情况下,您可以使用默认的"else";语句为special.append(c)
.
public void printString()
{
String input = "asDftQ32$34h";
List<Character> numbers = new ArrayList<>();
List<Character> letters = new ArrayList<>();
List<Character> specialChars = new ArrayList<>();
for (char current: input.toCharArray()) {
if(Character.isDigit(current))
{
numbers.add(current);
}
else if(Character.isAlphabetic(current))
{
letters.add(current);
}
else
specialChars.add(current);
}
System.out.println("All Letters In String :"+ letters);
System.out.println("All Numbers In String :"+ numbers);
System.out.println("All Special Characters In String :"+ specialChars);
}
使用字符API
由于您显然可以使用正则表达式,因此您可以使用字符类来简化此工作:
String str = "asDftQ32$34h";
System.out.println("character: " + str.replaceAll("\P{L}", ""));
System.out.println("number: " + str.replaceAll("\P{N}", ""));
System.out.println("special: " + str.replaceAll("\p{Alnum}", ""));