Wednesday, 28 June 2017

java - Find substring within a string





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");
}
}
}

Answer



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");
}

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...