判断字符在字符串中出现与否的四种方法
在 Java 中,判断一个字符是否在字符串中出现有多种方法。以下是几种常见的方法:
方法一:使用 String.indexOf(char ch)
indexOf 方法返回指定字符在字符串中第一次出现的索引,如果字符不存在则返回 -1。
public static void main(String[] args) {
String str = "!@#$%^&*()-+";
char ch = '@';
if (str.indexOf(ch) != -1) {
System.out.println(ch + " 在字符串中出现");
} else {
System.out.println(ch + " 不在字符串中出现");
}
}
方法二:使用 String.contains(CharSequence s)
contains 方法用于判断字符串是否包含指定的字符序列。需要注意的是,contains 方法接受 CharSequence 参数,因此需要将字符转换为字符串。
public static void main(String[] args) {
String str = "!@#$%^&*()-+";
char ch = '@';
if (str.contains(String.valueOf(ch))) {
System.out.println(ch + " 在字符串中出现");
} else {
System.out.println(ch + " 不在字符串中出现");
}
}
方法三:使用正则表达式 String.matches(String regex)
matches 方法用于判断字符串是否匹配给定的正则表达式。你可以构造一个正则表达式来检查字符是否在字符串中。
public static void main(String[] args) {
String str = "!@#$%^&*()-+";
char ch = '@';
if (str.matches(".*" + Pattern.quote(String.valueOf(ch)) + ".*")) {
System.out.println(ch + " 在字符串中出现");
} else {
System.out.println(ch + " 不在字符串中出现");
}
}
方法四:使用 StringBuilder 或 StringBuffer
虽然这种方法不太常用,但也可以通过构建一个包含所有特殊字符的字符串来检查。
public static void main(String[] args) {
String str = "!@#$%^&*()-+";
char ch = '@';
StringBuilder sb = new StringBuilder(str);
if (sb.indexOf(String.valueOf(ch)) != -1) {
System.out.println(ch + " 在字符串中出现");
} else {
System.out.println(ch + " 不在字符串中出现");
}
}