+ 2

String comparison

Could anyone please tell me, how could i compare an user input string with the already defined string

14th Sep 2017, 3:15 PM
vinay megharaj
vinay megharaj - avatar
2 Answers
+ 4
Make sure you utilize nextLine() with your scanner so you can obtain the entire string, rather than just the first word. After you've done that, use the String method `compareTo()` to compare the strings. If it's not a match, it'll return an int value of 0, and if it does match, it'll be something other than 0. Hope this helps. Good luck! https://code.sololearn.com/cVBO1OKL3fzH/#java import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String inputStr = ""; String knownStr = "This is already known."; inputStr = scnr.nextLine(); System.out.println("User String: " + inputStr); System.out.println("Known String: " + knownStr); System.out.print("Comparison: "); if(inputStr.compareTo(knownStr) == 0) { System.out.println("Strings match!"); } else { System.out.println("Strings do not match!"); } } }
14th Sep 2017, 3:37 PM
AgentSmith
+ 3
By the way, it's worth mentioning, that it compares the strings very literally. So that means it's case-sensitive and "this is already known." and "This is already known." is technically different strings. int compareToIgnoreCase(String str) ^That'll let you compare and ignore the casing of the letters if you need that option. Good luck to you!
14th Sep 2017, 3:47 PM
AgentSmith