Write a program, String Search, that takes in two strings as program arguments p
ID: 3553364 • Letter: W
Question
Write a program, String Search, that takes in two strings as program arguments prints the number of occurrences of the first string
in the second string, and prints the position of the first occurrence of the first string in the second string.
Requirements
1.
Your program will check if two program arguments were provided. If not, print a short warning message and exit.
2. You will define a method searchString:
public static int searchString(char[] needle, char[] haystack)
This method will return the position of the first occurrence of needle in haystack, or -1 if it does not occur.
3. You will define a method getFrequency:
public static int getFrequency(char[] needle, char[] haystack)
This method will return the number of times the string represented by needle occurs in haystack, or -1 if it does not occur.
4.You MUST !!!!!!!use the toCharArray method Idemonstrated to manipulate strings as arrays of characters
Explanation / Answer
public static void main(String[] args) {
int nargs = args.length;
if(nargs < 2) {
System.out.println("Provide two arguments");
} else {
System.out.println(searchString(args[0].toCharArray(), args[1].toCharArray()));
System.out.println(getFrequency(args[0].toCharArray(), args[1].toCharArray()));
}
}
public static int searchString(char[] needle, char[] haystack) {
int nsize = needle.length;
int hsize = haystack.length;
for(int i = 0; i < hsize; i++) {
int j;
for(j = 0; j < nsize; j++) {
if(i+j >= hsize) {
break;
}
if(needle[j] != haystack[i+j]) {
break;
}
}
if(j == nsize) {
return i+1;
}
}
return -1;
}
public static int getFrequency(char[] needle, char[] haystack) {
int freq = 0;
int nsize = needle.length;
int hsize = haystack.length;
for(int i = 0; i < hsize; i++) {
int j;
for(j = 0; j < nsize; j++) {
if(i+j >= hsize) {
break;
}
if(needle[j] != haystack[i+j]) {
break;
}
}
if(j == nsize) {
freq++;
}
}
if(freq == 0)
return -1;
else
return freq;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.