我有一项无法完成的编程任务。这一部分正在扼杀我。
接受用户的一些文字。接受需要搜索的字符串。您的程序应该打印在文本中找到的字符串的出现次数以及找到该模式的位置。请查看以下示例输出:
示例输出: 输入文字:“叫我以实玛利。几年前 - 没关系多长时间 - 我的钱包里没有钱,也没有什么特别令我感兴趣的,我觉得我会稍微航行一下,看看这个世界的水域。这是我驱除脾脏和调节血液循环的一种方式“
要搜索的字符串 - “几年前”
出现次数 - 1
找到职位 - 18
这是我的功能:
void getText()
{
string itext, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
cin >> itext;
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
char text[itext.length()];
char search[word.length()];
for(int i = 0; i < itext.length(); i++)
{
for(int j = 0; j < word.length(); j++)
{
if(text[i] == search[j])
{
position = i;
cout << position;
}
}
}
}
答案 0 :(得分:2)
这可能会让你开始:(来自Knuth-Morris-Pratt算法的伪代码)
algorithm kmp_search:
input:
an array of characters, S (the text to be searched)
an array of characters, W (the word sought)
output:
an integer (the zero-based position in S at which W is found)
define variables:
an integer, m ← 0 (the beginning of the current match in S)
an integer, i ← 0 (the position of the current character in W)
an array of integers, T (the table, computed elsewhere)
while m + i < length(S) do
if W[i] = S[m + i] then
if i = length(W) - 1 then
return m
let i ← i + 1
else
if T[i] > -1 then
let m ← m + i - T[i], i ← T[i]
else
let i ← 0, m ← m + 1
(if we reach here, we have searched all of S unsuccessfully)
return the length of S
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
编辑:更简单并使用c ++ std库:
#include <string>
#include <vector>
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = 0;
int matches = 0;
std::vector<size_t> positions;
while( found = str.find(str2) != std::string::npos) {
matches++;
positions.push_back(found);
}
}
答案 1 :(得分:0)
如果您在此任务中使用std :: string而不是char [],则可以使您的生活更轻松。您所要做的就是将文本加载到std :: string中,然后使用其中的find方法,如下所述: http://www.cplusplus.com/reference/string/string/find/
顺便说一下,我不确定这些行是否可以工作,因为只能使用常量表达式长度创建非动态数组
char text[itext.length()];
char search[word.length()];