Java 从字符串中搜索并计数一个单词
我需要一种只使用Java 从字符串中搜索并计数一个单词,java,string,pattern-matching,Java,String,Pattern Matching,我需要一种只使用length()、charAt()、toUpperCase()和toLowerCase()方法在文件中查找单词的方法 从长远来看,我将使用它作为一个文件,但为了练习,我将使用一个简单的字符串 这就是我要做的: public class WordSearch { public static void main(String [] args) { String str = "This is a sentence I am using as an example
length()
、charAt()
、toUpperCase()
和toLowerCase()方法在文件中查找单词的方法
从长远来看,我将使用它作为一个文件,但为了练习,我将使用一个简单的字符串
这就是我要做的:
public class WordSearch
{
public static void main(String [] args)
{
String str = "This is a sentence I am using as an example example Example.";
String word = "example";
int wordCounter = 1;
for(int i; i < str.length(); i++)
{
if(str.charAt(i) == ' ')
wordCounter++;
}
}
}
公共类单词搜索
{
公共静态void main(字符串[]args)
{
String str=“这是我正在使用的示例句子。”;
String word=“示例”;
int字计数器=1;
对于(int i;i
以下是如何在满足您的要求的同时完成此操作的概述
- 将文件作为字符串加载到内存中。使文件字符串和单词字符串均为小写
- 创建一个计数器,跟踪找到的单词数量。最初将其设置为
0
- 从第一个字符循环到最后一个字符。如果您使用的字符与单词的第一个字符匹配,则递增计数器。然后,对于下一个字符,请查看它是否与单词的第二个字符匹配,如果匹配,请再次递增计数器,依此类推。如果字符不匹配,当计数器等于找到的单词长度时,将计数器重置为
0
注意:使用扫描仪并逐字符读取是完成此任务的一种更有效的内存方式。好奇。。不管怎么说,这是一个很好的项目。我想使用的所有String和StringBuilder方法我根本无法使用它们。我知道我必须使用for循环,但我不知道如何理解你的意思。。。我是在为循环或多个if语句制作嵌套的for语句。。。
String text = "This is a ship shipping-ship, shipping shipping ships";
String word = "shipping";
String text1 = text.contains(" " + word + " ") ? text.replace(" " + word + " ", "") : text;
System.out.println((text.length() - text1.length()) / word.length());