0

I wrote a code to find a substring within a string in java but i want to know is there a short way to do this or is there a inbuilt function to do this.

Here's the code :

import java.util.*;
class substr 
{
    public static void main (String args [])
    {
        String str1 = new String();
        String str2 = new String();
        String str3 = new String();
        int check=1,k;
        Scanner obj= new Scanner (System.in);
        System.out.println("Enter a string");
        str1=obj.nextLine();
        System.out.println("Enter Sub String");
        str2=obj.nextLine();
        int len=str1.length();
        System.out.println(check);
        for( int c = 0 ; c < len&&check!=0 ; c++ )
        {
            for( int i = 1 ; i <= len - c&& check!=0 ; i++ )
            {
                str3 = str1.substring(c, c+i);
                if (str2.equals(str3))
                {   
                    check=0;
                }
            }
       }
       System.out.println(check);
       if (check==0)
       {
           System.out.println("Sub String");
       }
       else if ( check==1)
       {
           System.out.println("No");
       }
    }
}
Kristian Barrett
  • 3,574
  • 2
  • 26
  • 40
  • 2
    Check [String#indexOf](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(java.lang.String)) and [String#contains](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#contains(java.lang.CharSequence)) – BackSlash Mar 30 '14 at 14:54
  • [String#contains](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence))? – Alexis C. Mar 30 '14 at 14:54
  • It is not clear what you are asking. You actually do use substring method already. So where is the problem? – donfuxx Mar 30 '14 at 14:54
  • @donfuxx i just want to reduce my loc(line of codes) and to find the other ways to do this – user3478298 Mar 30 '14 at 15:03

1 Answers1

1

If you are asking for a way to do what your code does (check if a string is substring of another string), you can use String#contains:

if(str1.contains(str2)) {
    System.out.println("Sub String");
} else {
    System.out.println("No");
}


You can also use String#indexOf:
if(str1.indexOf(str2)>=0) {
    System.out.println("Sub String");
} else {
    System.out.println("No");
}
BackSlash
  • 21,927
  • 22
  • 96
  • 136