Java中如何知道给定字符串是否是另一个字符串的子字符串
你好 我必须计算给定的字符串是否是更大字符串的子字符串。 例如,
String str = "Hallo my world";
String substr = "my"
方法“contains”应该返回 true,因为 str 包含 substr(否则返回 false)。
我在 String 类中寻找类似“包含”的内容 但我没有找到。我认为唯一的解决方案是使用 模式匹配。如果是这种情况,这将是更好(最便宜)的方法 要这样做吗?
谢谢!
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"
The method "contains" should return true because str contains substr (false otherwise).
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
您可以使用 .substring(int beginIndex,int lastIndex) 来检查此程序。示例代码如下:-
You can use .substring(int beginIndex,int lastIndex) to check this program. Sample code goes as below:-
使用indexOf,如果没有匹配,它将返回-1(contains是在1.5中添加的,也许您使用的是较旧的jdk?)请参阅JDK 1.4.2 中 String 类中的“contains(CharSequence s)”方法了解详细信息
use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details
有一个
contains()
方法!它是在 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:这是您可以使用的通用方法
here is a general method that you can use
这将检查 s2 是否是 s1 的子字符串。
This checks if s2 is a substring of s1.
我认为有一个 String 函数可以满足您的要求:String.indexOf(String)。
请参阅此链接: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
那么,你可以编写这个函数:
I think there is a String function that does just what you are asking: String.indexOf(String).
See this link: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
So, then you could write this function:
String.indexOf(substr) 复杂度是 O(n2) .. Luixv 提出了一种更便宜的解决方案.. 但就 而言,我知道没有比当前算法更好的算法了。
String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.
通过这个方法。
访问棘手的代码
Go through this method.
visit for tricky code
*它们中的任何子字符串都将以子字符串的第1位的形式进行计数*
*In their any sub string will be count by the form of 1th place of string of substring *
考虑以下代码:
Consider the following code: