Develop a Java program with a method for comparing two strings.
Question
Develop a Java program with a method for comparing two strings.
Solution
Sure, here is a simple Java program that includes a method for comparing two strings:
public class StringComparator {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
int result = compareStrings(str1, str2);
if(result == 0) {
System.out.println("The strings are equal.");
} else if(result < 0) {
System.out.println("The first string is less than the second string.");
} else {
System.out.println("The first string is greater than the second string.");
}
}
public static int compareStrings(String s1, String s2) {
return s1.compareTo(s2);
}
}
In this program, we have a compareStrings method that uses the compareTo method of the String class to compare two strings. The compareTo method returns 0 if the strings are equal, a value less than 0 if the first string is lexicographically less than the second string, and a value greater than 0 if the first string is lexicographically greater than the second string.
Similar Questions
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace() .
Fill the below code to compare two strings and print "yes" if they are same else print "no".Don't consider the case. Example, if the strings are "Good" and "good" the output should be "yes".Code : Scanner sc=new Scanner(System.in); String s1=sc.next(); String s2=sc.next(); if() System.out.println("yes"); else System.out.println("no");
The program needs to compare two given strings lexicographically and output the difference between them. (using compareTo() function)If the first string is greater than the second string, it should output a positive value, If they are equal it should output 0If the first string is less than the second string, it should output a negative valueInput format :The first line of the input consists of a string.The second line of the input consists of a string.Output format :The output should display the following constraintsNote :If (string1 > string2), it returns a positive value (the difference between the characters).If both the strings are equal lexicographically, i.e., (string1 == string2), it returns 0.If (string1 < string2), it returns a negative value (the difference between the characters).Sample test cases :Input 1 :harryharryOutput 1 :0Input 2 :helloworldOutput 2 :-15Input 3 :tiger lionOutput 3 :8
What is the function to compare two strings lexicographically in C programming?
Write a C program to compare two strings character by character.Read the string using character pointer.Pass the character pointer to a function "compare" and print equal/not equal.Sample InputcatCatSample Outputnot equal
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.