gpt4 book ai didi

java - 输入一个句子并检查它是否包含用户输入的任何单词,同时打印计数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:31 24 4
gpt4 key购买 nike

我正在用 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<String> lst = new ArrayList<String>();

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 - 输入一个句子并检查它是否包含用户输入的任何单词,同时打印计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30451041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com