判断字符出现次数,可以使用循环遍历字符串并计数(使用循环遍历字符串的每个字符,然后通过判断字符是否与目标字符相等来计数)只能判断单字符出现次数,不太方便,建议使用正则表达式replace方法
replace 方法用于将字符串中的一部分内容替换为另一个内容。它有两种常用的重载形式:
replace(char oldChar, char newChar):
这种形式的 replace 方法将字符串中所有的 oldChar 字符替换为 newChar 字符。
replace(CharSequence target, CharSequence replacement):
这种形式的 replace 方法将字符串中所有的 target 字符序列替换为 replacement 字符序列。
String str = "Hello, World!"; String replacedStr = str.replace('o', 'a'); System.out.println(replacedStr); // 输出结果为 "Hella, Warld!" String replacedStr2 = str.replace("World", "Java"); System.out.println(replacedStr2); // 输出结果为 "Hello, Java!"
String s = "java";
String ss = "java,java.javass.javahello,javascript.java";
//将字符串ss中的字符串s替换为空,用ss-替换过后的字符串长度,即为字符串s出现的总长度
//再除以字符串s的长度,即为s出现的次数
int count = (ss.length() - ss.replace(s, "").length())/s.length();
System.out.println(count);
判断字符串有没有大写字母、汉字、数字及标准的手机号
public class RegExp2 {
public static void main(String[] args) {
String str = "hEllo world1212中国13876776756";
boolean f = true;
//将字母遍历出来,比较看是否含大写字母
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c < 'Z') {
f = false;
break;
}
}
if (f) {
System.out.printf("%s:有大写字母",str);
} else {
System.out.printf("%s:有大写字母",str);
}
}
}
用正则表达式判断
matches是 Java 中用于判断一个字符串是否匹配某个正则表达式的方法。它的使用方法是调用字符串对象的
matches
方法并传入对应的正则表达式作为参数。该方法返回一个布尔值,表示字符串是否完全匹配正则表达式。
public class RegExp3 {
public static void main(String[] args) {
String str = "hEllo world1212中国13876776756";
boolean f = true;
if (str.matches(".*[A-Z].*")) {
System.out.printf("%s:有大写字母",str);
}else {
System.out.printf("%s:没有大写字母",str);
}
System.out.println();
//汉字的Unicode 编码范围
if (str.matches(".*[\\u4e00-\\u9fa5].*")) {
System.out.printf("%s:有汉字",str);
}else {
System.out.printf("%s:没有汉字",str);
}
System.out.println();
if (str.matches(".*[0-9].*")) {
System.out.printf("%s:有数字",str);
}else {
System.out.printf("%s:没有数字",str);
}
System.out.println();
//格式为1开头,第二个只能为3,5,8,后面再加上9位数字
if (str.matches(".*1[358][0-9]{9}.*")){
System.out.printf("%s:有电话号码",str);
}else {
System.out.printf("%s:没有电话号码,str");}
}
}