在Java中,有多种方法可以用来查找字符串中的子字符串。以下是一些常用的方法:
indexOf() 方法
-1。String str = "Hello, World!";
int index = str.indexOf("World"); // 返回 7
lastIndexOf() 方法
-1。String str = "Hello, World! World!";
int index = str.lastIndexOf("World"); // 返回 13
contains() 方法
true;否则返回 false。String str = "Hello, World!";
boolean contains = str.contains("World"); // 返回 true
startsWith() 方法
true;否则返回 false。String str = "Hello, World!";
boolean startsWith = str.startsWith("Hello"); // 返回 true
endsWith() 方法
true;否则返回 false。String str = "Hello, World!";
boolean endsWith = str.endsWith("World!"); // 返回 true
matches() 方法
true;否则返回 false。String str = "Hello, World!";
boolean matches = str.matches("Hello, .*!"); // 返回 true
replace() 或 replaceAll() 方法
replace() 方法用于替换字符串中的所有匹配项。replaceAll() 方法使用正则表达式进行替换。String str = "Hello, World!";
String replacedStr = str.replace("World", "Java"); // 返回 "Hello, Java!"
split() 方法
String str = "apple,orange,banana";
String[] fruits = str.split(","); // fruits 数组为 ["apple", "orange", "banana"]
这些方法提供了不同的方式来查找和处理字符串中的数据。根据具体的需求,可以选择合适的方法来实现字符串的查找和操作。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。