判断字符java
‘壹’ java中怎么判断一个字符串中包含某个字符或字符串
Java中字符串中子串的查找共有四种方法,如下:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
示例
下面的示例说明了 indexOf 方法的用法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function IndexDemo(str2){
var str1 = "BABEBIBOBUBABEBIBOBU"
var s = str1.indexOf(str2);
return(s);
}
public class FirstDemo {
/**
*API中String的常用方法
*/
// 查找指定字符串是否存在
public static void main(String[] args) {
String str1 = "abcdefghijklmnabc";
// 从头开始查找是否存在指定的字符
System.out.println(str1.indexOf("c"));
// 从第四个字符位置开始往后继续查找
System.out.println(str1.indexOf("c", 3));
//若指定字符串中没有该字符则系统返回-1
System.out.println(str1.indexOf("x"));
}
‘贰’ java 怎么判断字符串中是否含有一个符号
1、首先在打开的java程序中,需要引入hutool的jar包,如下图所示。
‘叁’ Java 判断字符串是否含有所有特殊符号
判断字符串是否含有所有特殊符号的Java程序如下(用正则表达式判断)
正则表达式 ^[0-9A-Za-zu4e00-u9fa5]+$表示字符串中只有数字英文和汉字
public class AA {
public static void main(String[] args) {
String str="abc我们mn32opQrst";
String regex="^[0-9A-Za-zu4e00-u9fa5]+$";
if(str.matches(regex)==true){
System.out.println("字符串不含有所有特殊符号");
}else{
System.out.println("字符串含有所有特殊符号");
}
}
}
‘肆’ java中怎么判断一个字符串中包含某个字符或字符串
方法:
使用String类的indexOf()方法可以判断一个字符串是否在另一个字符串中出现,其方法原型为:
intjava.lang.String.indexOf(Stringarg0)
如果字符串arg0出现在源字符串中,返回arg0在源字符串中首次出现的位置。
Java程序:
publicclassMain{
publicstaticvoidmain(String[]args){
Stringkey="wo";
char[]arr={'H','e','l','l','o',',','','w','o','r','l','d','!'};
Stringsource=String.valueOf(arr);
if(source.indexOf(key)>=0){
System.out.printf(""%s"中包含"%s"",source,key);
}
else{
System.out.printf(""%s"中不包含"%s"",source,key);
}
}
}
运行测试:
"Hello,world!"中包含"wo"