返回一个值,该值指示指定的 String 对象是否出现在此字符串中。
下面的代码示例确定字符串“fox”是否为熟悉的引文中的子字符串。
// This example demonstrates the String.Contains() methodusing System;class Sample {
public static void Main() {
string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
}
}
String contains api如下:
/**
* Returns true if and only if this string contains the specified sequence of char values.
*
* @param s the sequence to search for
* @return true if this string contains <code>s</code>, false otherwise
* @throws NullPointerException if <code>s</code> is <code>null</code>
* @since 1.5
*/
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
注意:
public class XMLTypeDemo {
public static void main(String[] args) {
String str = "我们的灵魂都应该是自由的,哪怕有圣洁与污秽之分。";
// true
System.out.println(str.contains("自由"));
// java.lang.NullPointerException
System.out.println(str.contains(null)); //null.toString() 会报空指针
}
}
注意它参数类型是CharSequence,不支持正则表达式;
如果你要判断的话需要是用String.matches()方法;