如何检查子字符串是否在字符串的末尾

How to check if a substring is at the end of a string

我有一个字符串

String str = "Hello there how are you" 

和一个子字符串

String substr = "how are you". 

我正在检查字符串是否包含这样的子字符串:

if (str.toLowerCase().contains(substr.toLowerCase())) {
    // now check if substr is the last part of str
}

如果子字符串在字符串中,我想检查子字符串是否是字符串的最后一部分。无论如何我可以做到这一点吗?谢谢!

您需要 String.endsWith() 方法:

if (str.toLowerCase().endsWith(substr.toLowerCase()) 

您可以使用 endsWith 方法而不是多步骤方法,如果这就是您想要了解的全部内容:

if (str.toLowerCase().endsWith(substr.toLowerCase())) {

如果你需要知道两者(因为你有下面第二个if之外的内容),and/or做一些更高级的事情,你可以使用单独的行:

if (str.toLowerCase().contains(substr.toLowerCase())) {
    if (str.toLowerCase().endsWith(substr.toLowerCase())) {
    }
}