Java:1.将一个英文字符串中大写字符和小写字符分开显示。 2.统计一个英文字符串中各个字母出现的次数。需要源码
时间: 2023-11-12 15:03:51 浏览: 80
Java编程实现统计一个字符串中各个字符出现次数的方法
1. 代码实现如下:
```java
public class SeparateChar {
public static void main(String[] args) {
String str = "This is a test String";
String upper = "";
String lower = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isUpperCase(c)) {
upper += c + " ";
}
else if (Character.isLowerCase(c)) {
lower += c + " ";
}
}
System.out.println("Uppercase letters: " + upper);
System.out.println("Lowercase letters: " + lower);
}
}
```
2. 代码实现如下:
```java
public class CountLetters {
public static void main(String[] args) {
String str = "This is a test String";
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isLetter(c)) {
count[Character.toLowerCase(c) - 'a']++;
}
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
System.out.println((char)('a' + i) + ": " + count[i]);
}
}
}
}
```
阅读全文