In: Computer Science
This exercise will test your ability to use the basic instance methods of String. The exercise is to create a program that compares two Strings ignoring the case and returns the offset between the first two distinct characters in the two Strings from left to right.
All the input strings have five characters.
For this exercise, compareToIgnoreCase() and compareTo() methods are not allowed.
Example 1, "London" and "Lately" will return the offset between 'o' and 'a', which is 14
Example 2, "London" and "lately" will return the offset between 'o' and 'a', which is 14
Example 3, "LONDON" and "lately" will return the offset between 'o' and 'a', which is 14
Example 4, "LONDON" and "Loathe" will return the offset between 'n' and 'a', which is 13
Example 4, "LONDON" and "london" will return 0
The class name should be: Lab14_CustomizedStringComparison
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter string1: ");
String str1= sc.next();
System.out.print("Enter string2: ");
String str2= sc.next();
str1=str1.toLowerCase();
str2=str2.toLowerCase();
int ans;
ans=compare(str1,str2);
System.out.println("Offset: "+ans);
}
public static int compare(String str1,String str2)
{
int ans=0;
for(int i=0,j=0;i<str1.length()&&j<str2.length();i++,j++)
{
int t1= (int)str1.charAt(i);
int t2=(int)str2.charAt(j);
if (t1-t2 !=0){
ans=Math.abs(t1-t2);
break;
}
}
return ans;
}
}