compare two string in java without built-in function.

 import java.util.*;

public class code {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
     System.out.println("enter string 1=");
     String s=sc.nextLine();
     System.out.println("enter string 2=");
     String t=sc.nextLine();
     boolean flag=true;
     int ans=0;
     int i=0,j=0;
     while(i<s.length() && j<t.length()){
            int as1=s.charAt(i);
            int as2=t.charAt(j);
            if(as1!=as2){
            flag=false;
            ans=(as1-as2);
            break;
            }
            i++;
            j++;
        }
    if(flag==true && s.length()==t.length())
        System.out.println(ans);
    else if(i==s.length() && j!=t.length() && flag==true){
        while(j<t.length()){
            ans++;
            j++;
        }
    System.out.println(-ans);
    }
    else if(j==t.length() && i!=s.length() && flag==true){
        while(i<s.length()){
            ans++;
            i++;
        }
         System.out.println(ans);
    }
    else
        System.out.println(ans);
    }
}

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.