233k views
3 votes
1. Write a program that uses String method regionMatches to compare two strings input by the user. The program should prompt the user to enter two strings, the starting index in the first string, the starting index in the second string, and the number of characters to be compared. The program should print whether or not the strings are equal. (Ignore the case of the characters during comparison.) This is a sample run of your program: Enter·first·string:Have·yourself·a·merry·little·Christmas.↵ Enter·second·string:It's·beginning·to·look·a·lot·like·christmas.↵ Enter·starting·index·for·first·string:29·↵ Enter·starting·index·for·second·string:34·↵ Enter·number·of·characters·to·be·compared:9↵ true↵

1 Answer

1 vote

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. System.out.print("Input first string: ");
  6. String string1 = input.nextLine();
  7. System.out.print("Input second string: ");
  8. String string2 = input.nextLine();
  9. System.out.print("Start index for first string: ");
  10. int i1 = input.nextInt();
  11. System.out.print("Start index for second string: ");
  12. int i2 = input.nextInt();
  13. System.out.print("Number of characters to be compared: ");
  14. int n = input.nextInt();
  15. if(string1.regionMatches(true, i1, string2, i2, n)){
  16. System.out.println("The strings are equal.");
  17. }
  18. else{
  19. System.out.println("The strings are not equal.");
  20. }
  21. }
  22. }

Step-by-step explanation:

The solution code is written in Java.

Firstly create a Scanner object (Line 5).

Next, use the Scanner object and nextLine method to get user input for string1 and string 2 (Line 7 - 11 )

Next, proceed to get the start index for first and second string using nextInt (Line 14 and Line 17) and followed with number of characters to be compared (Line 20).

Use the regionMatches method by passing all the input values as argument (Line 22) and if we pass the sample input we shall get the true and the program shall display the message "The strings are equal." (Line 22- 23)

User Coxer
by
5.3k points