简体   繁体   English

字符串操作Java搜索subString序列

[英]String Operation Java to search a subString sequence

We have a string declared as follows: String strString="This is a test statement to find a sub sequence of string"; 我们有一个声明为以下字符串:String strString =“这是一个测试语句,用于查找字符串的子序列”;

There doesn't seem to be a method in String class that will search a sub sequence, like: Given String strString2="test ststement to find"; 在String类中似乎没有一种方法可以搜索子序列,例如:给定String strString2 =“ test ststement to find”;

Here strString2 is a sub sequence of strString, Is there a way to find without character compare? 这里的strString2是strString的子序列,有没有没有字符比较的查找方法?

I believe you are looking for String#indexOf(String) . 我相信您正在寻找String#indexOf(String) That will also give you the location in the string if it's found. 如果找到,它还将为您提供字符串中的位置。

String.contains(CharSequence s) String.contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values. 当且仅当此字符串包含指定的char值序列时,才返回true。

You can do something like this. 你可以做这样的事情。

String strString="This is a test statement to find a sub sequence of string";
strString2="test ststement to find";
if(strString.contains(strString2)){
    //Do something. 
}

The condition to check existence of strString2 in strString is: 检查strString中strString2是否存在的条件是:

strString.indexOf(strString2) >= 0

or 要么

strString.contains(strString2)

You could try this: 您可以尝试以下方法:

string1.contains(string2);`

Please note that it will throw a NullPointerException if string2 is null . 请注意,如果string2null ,它将抛出NullPointerException You have to make sure that the string2 is not null before trying the comparison; 尝试比较之前,必须确保string2不为null。 the other situations should handle as you would expect. 其他情况应按预期处理。 You can also use the toLowerCase() method along with contains() method if you would like to ignore case. 如果您想忽略大小写,也可以将toLowerCase()方法与contains() toLowerCase()方法一起使用。

string1.toLowerCase().contains(string2.toLowerCase())

Also for older versions, you could use indexOf() method. 同样对于旧版本,您可以使用indexOf()方法。 If string2 is not in string1 , indexOf will give you -1 . 如果string2不在string1indexOf将为-1 Here also you must ensure beforehand that both Strings are not null though to avoid a NullPointerException . 在这里,您还必须事先确保两个String都不为null以避免NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM