1、输入一个任意字符串,找出所有的数字?
String str = "sdfsafdsafd324532432fewfwst435r3q425jnsfwqe243554";
Pattern pattern = Pattern.compile("\\d+"); // 创建正则表达式模式
Matcher matcher = pattern.matcher(str); // 创建匹配器对象
while (matcher.find()) { // 迭代匹配的结果
System.out.println(matcher.group());
}
//方法二
String s = str.replaceAll("[^0-9]", "");
System.out.println("s = " + s);
扩展问题:中文字符串对应的十进制数字,19968-40869
private static void computer() {
// char ch = '\u4e00'; 16进制
// char ch = 19968; 10进制,19968-40869
Random random = new Random();
int i = 0;
for (;;){
i++;
int ch = random.nextInt(40870 - 19968) + 19968;
System.out.println("ch = " + (char)(ch));
if (ch == '林'){
System.out.println(ch);
System.out.println(i);
break;
}
}
}
2、统计一串含字母的字符串中每个字母出现的次数
private static void count() {
String str = "The so-called 'multifunctional' is not adding many elements, " +
"but subtracting them. Only by leaving blank can ten thousand possibilities be created.";
// 创建HashMap用于存储字母和出现次数
Map<Character, Integer> countMap = new HashMap<>();
// 遍历字符串的每个字符
for (char c : str.toCharArray()) {
// 判断是否为字母
if (Character.isLetter(c)) {
// 将字母转为小写形式
char lowercase = Character.toLowerCase(c);
// 更新字母的出现次数,使用Map的getOrDefault方法来获取该字母已有的计数并加一
countMap.put(lowercase, countMap.getOrDefault(lowercase, 0) + 1);
}
}
// 遍历Map输出每个字母及其出现次数
for (char c : countMap.keySet()) {
int count = countMap.get(c);
System.out.println(c + ": " + count);
}
}
3、数组倒置的方法
private static void listReverse() {
int a[] = {1, 2, 3, 4, 5};
int length = a.length;
//length除以2:由于是对称倒置,循环只需执行数组长度的一半即可完成倒置。以避免在循环条件和索引计算中多次重复执行
for (int i = 0; i < length / 2; i++) {
int temp = a[i];
a[i] = a[length - 1 - i];
a[length - 1 - i] = temp;
}
//循环结束后再for循环输出整个数组
for (int num : a) {
System.out.println("a = " + num);
}
}