在Java中,有多种方法可以用来查找字符串中的子串。以下是一些常用的方法:
indexOf() 方法
indexOf() 方法用于返回指定子串在此字符串中第一次出现处的索引。如果字符串中不包含子串,则返回 -1。String str = "Hello, World!";
String subStr = "World";
int index = str.indexOf(subStr);
System.out.println("子串的索引为: " + index); // 输出:子串的索引为: 7
lastIndexOf() 方法
lastIndexOf() 方法用于返回指定子串在此字符串中最后一次出现处的索引。如果字符串中不包含子串,则返回 -1。String str = "Hello, World! World!";
String subStr = "World";
int index = str.lastIndexOf(subStr);
System.out.println("子串的索引为: " + index); // 输出:子串的索引为: 13
contains() 方法
contains() 方法用于判断一个字符串是否包含另一个字符串,如果包含则返回 true,否则返回 false。String str = "Hello, World!";
String subStr = "World";
boolean contains = str.contains(subStr);
System.out.println("字符串是否包含子串: " + contains); // 输出:字符串是否包含子串: true
startsWith() 和 endsWith() 方法
startsWith() 方法用于判断一个字符串是否以指定的前缀开始,如果是则返回 true,否则返回 false。endsWith() 方法用于判断一个字符串是否以指定的后缀结束,如果是则返回 true,否则返回 false。String str = "Hello, World!";
String prefix = "Hello";
String suffix = "World!";
boolean startsWith = str.startsWith(prefix);
boolean endsWith = str.endsWith(suffix);
System.out.println("字符串是否以指定前缀开始: " + startsWith); // 输出:字符串是否以指定前缀开始: true
System.out.println("字符串是否以指定后缀结束: " + endsWith); // 输出:字符串是否以指定后缀结束: true
这些方法可以帮助你在Java中查找字符串中的子串。你可以根据实际需求选择合适的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。