Tuesday, 15 October 2013

A program to check whether a string is a substring of a given another string or not .

Here is the source code .....


       

import java.io.*;
public class P18 {
 public static void main(String args[]) {
  String s1 = "ur";
  String s2 = "gaurav";
  P18 ab = new P18();
  ab.isString(s1, s2);
 }

 void isString(String s1, String s2) {
  int k;

  if (s1.length() > s2.length()) {
   System.out.println("string is not substring");
   return;
  }

  for (int i = 0, s = 0; i < s2.length() - s1.length(); i++) {
   if (s2.charAt(i) == s1.charAt(s)) {
    for (k = i; k < i + s1.length(); k++) {
     if (s1.charAt(s) == s2.charAt(k)) {
      s++;
     } else {
      s = 0;
      break;
     }
    }
    if (k == i + s1.length()) {
     System.out.println("string is substring");
     return;
    }
   }

  }
  System.out.println("string is not the substring");
 }
}

       
 

No comments:

Post a Comment