在句子中查找单词
Finding words in sentences
我有一个编程作业无法完成。这一部分正在杀死我。
接受来自用户的一些文本。接受需要搜索的字符串。您的程序应该打印在文本中找到的字符串的出现次数,以及找到模式的位置。查看以下示例输出:
示例输出: 输入文本:"叫我以实玛利。几年前——不管确切地花了多久——我的钱包里很少或根本没有钱,在岸上也没有什么特别让我感兴趣的,我想我会航行一会儿,看看世界的水域。这是我驱除脾脏和调节血液循环的一种方式"
要搜索的字符串 - "几年前"
出现次数 – 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;
}
}
}
}
这可能会让你开始:(来自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);
}
}
如果你在这个任务中使用std::string而不是char[],你可以让你的生活更轻松。您所要做的就是将文本加载到 std::string 中,然后使用其 find 方法,如下所述:http://www.cplusplus.com/reference/string/string/find/
顺便说一句,我不确定这些行是否可以工作,因为您可以仅使用常量表达式长度创建非动态数组
char text[itext.length()];
char search[word.length()];
相关文章:
- 在C++中查找(奇怪的)字符串中的单词
- 从文件中查找单词并替换到其他文件中
- 在文本中查找半个单词"ABBA"的问题
- C++:如何用split查找单词?Regex
- 查找包含指定单词的行(从文件中)
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 在带有C++的txt文件中查找最长的单词
- 从文件的一行中查找数字的平均值,避免使用第一个单词
- 在文件中查找 10 个最长的单词
- 如何使我的单词查找更清晰、更高效
- 视觉C++查找以 "ing" 结尾且少于或等于 10 个字符的单词
- 如何在没有分隔符的大文本文件中查找所有字典单词
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 我如何在一串随机生成的字母I C 中查找一个单词
- 在 C++ 的句子中查找某个单词
- Qt使用QWebEngine查找单词功能
- 在向量中通过一个单词查找行
- 单词搜索难题:如何搜索一系列字母来查找单词
- C 查找并替换整个单词