java判断一个字符串是否包含另外一个字符串,java另外一个,要检查一个字符串是否包含
分享于 点击 30279 次 点评:196
java判断一个字符串是否包含另外一个字符串,java另外一个,要检查一个字符串是否包含
要检查一个字符串是否包含另外一个字符串需要使用indexOf()方法,如果indexOf方法返回大于等于0的值,则表示包含,若返回-1则表示字符串中不包含。
如下是示例代码:
/** * Main.java * * @author byrx.net */public class Main { /** * 检查字符串是否包含某个字符串 */ public void checkStringContains() { String haystack = "Programming in Java"; String needle1 = "Java"; String needle2 = "Pascal"; int index1 = haystack.indexOf(needle1); int index2 = haystack.indexOf(needle2); if (index1 != -1) System.out.println("The string contains the substring " + needle1); else System.out.println("The string does not contain the substring " + needle1); if (index2 != -1) System.out.println("The string contains the substring " + needle2); else System.out.println("The string does not contain the substring " + needle2); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().checkStringContains(); }}
上述代码的执行结果如下
The string contains the substring JavaThe string does not contain the substring Pascal
用户点评