如何知道给定字符串是否是Java中另一个字符串的子字符串 [英] How to know if a given string is substring from another string in Java
问题描述
Hi
如果给定的字符串是更大字符串的子字符串,我必须计算。
例如
Hi I have to compute if a given string is substring of a bigger string. For example
String str = "Hallo my world";
String substr = "my"
方法contains应返回true,因为str包含substr(否则为false)。
The method "contains" should return true because str contains substr (false otherwise).
我在String类
中寻找类似contains的东西,但我找不到它。我想唯一的解决方案是使用
模式匹配。如果这样做的话会更好(最便宜)
这样做?
I was looking for something like "contains" at the String class but I didn't find it. I suppose that the only solution is to use pattern matching. If this is the case which would be the better (cheapest) way to do this?
谢谢!
推荐答案
是 a 包含()
方法!它是在Java 1.5中引入的。如果您使用的是早期版本,则可以使用以下版本轻松替换它:
There is a contains()
method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:
str.indexOf(substr) != -1
这篇关于如何知道给定字符串是否是Java中另一个字符串的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!