java判断是否存在某个单词_java-要输入一个句子并检查它是否包含用户输入的任何单词,还要打印计数...

我正在使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值