您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,字符串查找通常指的是在一个字符串(source)中查找另一个字符串(target)的位置。以下是一些常用的技巧和方法:
indexOf()
方法:
String source = "Hello, World!";
String target = "World";
int index = source.indexOf(target); // 返回 7
lastIndexOf()
方法:
indexOf()
,但是它返回目标字符串在源字符串中最后一次出现的位置。int lastIndex = source.lastIndexOf(target); // 返回 7
contains()
方法:
boolean contains = source.contains(target); // 返回 true
startsWith()
和 endsWith()
方法:
boolean startsWith = source.startsWith("Hello"); // 返回 true
boolean endsWith = source.endsWith("!"); // 返回 true
matches()
方法:
boolean matches = source.matches("H.*o"); // 返回 true
replace()
或 replaceAll()
方法:
replace()
方法使用固定的字符串进行替换,而 replaceAll()
方法使用正则表达式进行替换。String replaced = source.replace("World", "Java"); // 返回 "Hello, Java!"
String replacedWithRegex = source.replaceAll("l+", "L"); // 返回 "HeLLo, WorLd!"
split()
方法:
String[] parts = source.split(", "); // 返回 ["Hello", "World!"]
使用正则表达式:
Pattern
和 Matcher
类来进行正则表达式的匹配。Pattern pattern = Pattern.compile(target);
Matcher matcher = pattern.matcher(source);
if (matcher.find()) {
int index = matcher.start(); // 返回目标字符串在源字符串中第一次出现的位置
}
在使用这些方法时,要注意区分大小写敏感性。例如,indexOf()
和 contains()
方法默认是区分大小写的。如果你需要进行不区分大小写的查找,可以将字符串转换为全小写或全大写再进行比较,或者使用相应的正则表达式标志(如 Pattern.CASE_INSENSITIVE
)。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。