试图在线性算法中查找字符串的出现次数

时间:2017-12-09 18:00:09

标签: java

好的,我重新格式化了我想要做的事情。输出必须返回以下值。

我知道我需要使用multidimesion循环进行迭代来检查每个角色,但是就如何去做而言我很难过。

String str = "what has the time"


value1 = "hatw hat has the time"
value2 = "wwhhaatt hhaas the time"
value3 = "what has thetime"


output line 1: 00001
output line 2: 00256
output line 3: 00000 

1 个答案:

答案 0 :(得分:0)

如果你习惯使用RegEx,它的方法和工作可以为你节省很多麻烦。

String str = "purrpppppllleeee ssaiyan purple saiyan";
String findStr = "purple saiyan";
String regexStr = "";
for(int i = 0; i < findStr.length(); i++)
{
    regexStr += findStr.charAt(i)+"+";
}
regexStr += "\\s*";
Pattern patt = Pattern.compile(regexStr);
Matcher m = patt.matcher(str);
int count = 0;
while(m.find())
{
    count++;
}

循环只是在findStr的每个字符后添加一个加号。

在字符后面添加加号告诉匹配器可能会多次出现该字母。

最后,匹配器找到短语findStr发生了多少次(以代码的形式)