我有一个字符串
"the dog jumped over the fox"
如果我执行string.contains("the")
,它将返回true
。有没有办法可以只取出 "the"
的第一个实例?
编辑:我意识到我的问题不明确。正如你们大多数人现在可能已经猜到的那样,我想找到它的第一个实例,将其“拉”出来,然后用“”替换它。
最佳答案
如果“pull out”是指删除,则可以使用String#replaceFirst
。
即
String sentence = "the dog jumped over the fox";
if (sentence.contains("the")) {
sentence = sentence.replaceFirst("the\\s*","");
}
关于Java .contains第一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735801/