我正在使用Java编写程序,其输出应如下所示:
Input the sentence
hello how how are you
enter code here
Input the word that has to be searched
how
Output :
the string is present and the count of the string how is : 2
I have written a program but i am not able to count the search string can anyone please help me on this and below is the code
我认为循环也存在问题,我能够找到句子中存在的字符串,但无法计数.
boolean contains = false;
/*Inputting the sentence*/
java.util.Scanner scn = new java.util.Scanner(System.in);
System.out.println("Input the sentence");
String s = scn.nextLine();
String[] lstarr = s.split(" ");
/*Inputting the string*/
java.util.Scanner scn2 = new java.util.Scanner(System.in);
System.out.println("Input the word to be searched");
String s2 = scn.nextLine();
String[] explst = s2.split(" ");
/*searching the input word */
if(s.contains(s2)){
contains = true;
System.out.println("Input word is present : " + s2);
}
else{
System.out.println("String " + s2 + "is not present");
}
ArrayList lst = new ArrayList();
Collections.addAll(lst, lstarr);
for(String str : lst) {
System.out.println(str + " " + Collections.frequency(lst, str));
}
}
解决方法:
试试下面的代码:
public static void main(String[] args) {
System.out.println("Input the sentence");
Scanner s = new Scanner(System.in);
String input = s.nextLine();
System.out.println("Input the word that has to be searched");
String word = s.nextLine();
String str = "";
int occurance = 0;
for(char c : input.toCharArray()) {
str += c;
if(str.length() == word.length()) {
if(str.equals(word)) {
occurance ++;
}
str = str.substring(1);
}
}
if(occurance > 0)
System.out.println("the string is present and the count of the given string is : " + occurance);
else
System.out.println("The string is not present");
}
标签:java
来源: https://codeday.me/bug/20191120/2042614.html