ibraheemkhalil
ibraheemkhalil

Reputation: 33

String partial match

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

Answers (5)

Michell Bak
Michell Bak

Reputation: 13242

This should do the trick:

if (s2.contains(s1))
    return s2;

Upvotes: 4

Kristian Moström
Kristian Moström

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

Lucifer
Lucifer

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

waqaslam
waqaslam

Reputation: 68167

Its pretty straight forward.

if(s2.contains(s1)){
    //do your stuff
}

Upvotes: 0

David Ganster
David Ganster

Reputation: 1993

You can use Java.String.indexOf(), as described here.

Upvotes: 0

Related Questions