JAVA: Consider the following scheme for storing words. Words are concatenated in
ID: 3838327 • Letter: J
Question
JAVA:
Consider the following scheme for storing words. Words are concatenated into one long string with no delimiters. A 2-dimensional array specifies the start position and the length of each word. For example, the words 'a' 'about' 'and' 'by' 'for' and 'with' would be
String:aaboutandbyforwith
Array:
0 | 1
1 | 5
6 | 3
9 | 2
11 | 3
14 | 4
Write an int valued method called find which has three parameters - the String of words, the array, and a String to search for. If the string to search for is a word in the first String, the method should return the start position of that word; otherwise, it should return -1.
Explanation / Answer
SearchString,.java
public class SearchString {
public static void main(String[] args) {
// Declaring variables
String str;
String firstString = "aaboutandbyforwith";
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
// Declaring a two dimensional array and initialized with values
int arr[][] = { { 0, 1 }, { 1, 5 }, { 6, 3 }, { 9, 2 }, { 11, 3 },
{ 14, 4 } };
// Getting the string entered by the user
System.out.print("Enter a string to search for :");
str = sc.next();
// calling the method
int res = find(firstString, arr, str);
// Based on the result value display the message
if (res != -1) {
System.out.println("Search string found at index " + res);
} else {
System.out.println("Search string not found.");
}
}
// This method will search for the user entered string in the firstString
private static int find(String firstString, int[][] arr, String str) {
int index;
for (int i = 0; i < arr.length; i++) {
index = arr[i][0];
// System.out.println(index);
if (arr[i][1] == str.length()) {
if (str.equals(firstString.substring(index, index + arr[i][1]))) {
return index;
}
}
}
return -1;
}
____________________
Output:
Enter a string to search for :with
Search string found at index 14
____________________
Output#1:
Enter a string to search for :hello
Search string not found.
________________Thak You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.