如何判断一个字符数组是否包含某个字符串

如题所述

方法:

使用String类的indexOf()方法可以判断一个字符串是否在另一个字符串中出现,其方法原型为:

int java.lang.String.indexOf(String arg0)

如果字符串arg0出现在源字符串中,返回arg0在源字符串中首次出现的位置。


Java程序:

public class Main {
public static void main(String[] args) {
String key = "wo";
char[] arr = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'};
String source= 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"

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-05-21
public class BString {
public static void main(String[] args) {
char[] a = {'q','w','q','f','r'};
String str = "qwq";
if(ifString(str,a))
System.out.println("包含");
else
System.out.println("不包含");

}
public static boolean ifString(String str,char[] a){
String s = new String(a);
return s.indexOf(str)!=-1;
}

}

相似回答