Reputation: 33
i want partial matching of string in java e.g
String s1 = "method";
String s2 = "this is wonderful method i am using ";
if s1 complete exists in s2 then s2 returns. any one has algorithm or other flexible code, Thank you in advance.
Upvotes: 1
Views: 5423
Reputation: 100
Easiest would be to use String.contains as in if( s2.contains(s1) ) return s2;
Or you could use regex to match
if( s2.matches("(?i).*" + s1 + ".*") )
{
return s2;
}
Might be a bit overkill though, but good to know a few different ways to do it.
Upvotes: 0
Reputation: 29632
You can use contains()
method of String
class, Please study the following example,
public class TestClass
{
private String getString ( String str1, String str2 )
{
if ( str2.contains (str1) )
{
return str2;
}
else
{
return "-1";
}
}
public static void main ( String args[] )
{
String s1 = "method";
String s2 = "this is wonderful method i am using";
TestClass tc = new TestClass();
System.out.println ( tc.getString(s1, s2) );
}
}
// Output
// this is wonderful method i am using
Upvotes: 0
Reputation: 68167
Its pretty straight forward.
if(s2.contains(s1)){
//do your stuff
}
Upvotes: 0