Blogs

Fastest String Compare Algorithm in Java
Author:Dixanta Bahadur Shrestha

Most of programming languages have their own way of "String Compare Algorithm" available. Ever wondered writing you own fastest String comparing algorithm ? I have written easiest way of comparing Strings in Java, but not only limited to Java, have written the algorithm in such a way that can be used in most of other programming languages too.

    
            /**
            * String compare Algorithm
            * Author Dixanta Bahadur Shrestha
            * Creators Institute of Business & Technology
            * Lalitpur, Nepal
            */
           package com.cibt.code;
           
           public class App {
               public static void main(String[] args) {
                   
                   String text="Creators";
                   String pattern="Creators";
                   int textLength=text.length();
                   int patternLength=pattern.length();
               
                   if(patternLength == textLength && text.charAt(0)==pattern.charAt(0) && text.charAt(textLength-1)==pattern.charAt(textLength-1) ){
                       int end=textLength-1;
                       boolean match=true;
                       for(int i=1;i<end;i++){
                           if(text.charAt(i)!=pattern.charAt(i) || text.charAt(end-1)!=pattern.charAt(end-1)){
                               match=false;
                               break;
                           }
                           end--;
                       }
                       if(match){
                           System.out.println("Pattern matched");
                       }else{
                           System.out.println("Pattern not matched");
                       }
                   }else{
                       System.out.println("Pattern not matched");
                   }
               }    
           }
    
Input
text = Creators pattern = Create
Output
Pattern not matched
Input
text = Creators pattern = Creatars
Output
Pattern not matched
Input
text = Creators pattern = Creators
Output
Pattern matched
Happing Coding !!

Previous