gpt4 book ai didi

c++ - 比较字符串的一部分

转载 作者:行者123 更新时间:2023-11-28 08:02:42 24 4
gpt4 key购买 nike

好的,这就是我想要完成的。

首先,下表只是我创建的示例,在我的作业中我不应该知道这些。这意味着我不知道他们将传递什么以及每个字符串的长度是多少。

我正在努力完成的一项任务是能够比较字符串的一部分

   //In Array `phrase`       // in array `word`
"Backdoor", 0 "mark" 3 (matches "Market")
"DVD", 1 "of" 2 (matches "Get off")
"Get off", 2 "" -1 (no match)
"Market", 3 "VD" 1 (matches "DVD")

所以你可以从上面的代码中看到,左边是一组数组,我将它们存储在我的类中,它们最多有 10 个单词

这是类定义。

class data
{
char phrase[10][40];
public:
int match(const char word[ ]);
};

所以我使用成员函数来访问这个私有(private)数据。

int data::match(const char word[ ])
{
int n,
const int wordLength = strlen(word);

for (n=0 ; n <= 10; n++)
{
if (strncmp (phrase[n],word,wordLength) == 0)
{
return n;
}
}

return -1;
}

上面我试图让它工作的代码是它应该匹配并且如果找到匹配则返回索引 n 如果没有找到应该总是返回 - 1

现在总是返回 10

最佳答案

你快完成了,但你的代码不完整,所以我在黑暗中拍摄一些东西。

代表一个索引的变量可能太多了。除非 ni 不同,否则您应该只使用一个。也尽量使用更具描述性的名称,pos 似乎代表了你正在搜索的文本的长度。

for (n=0 ; n <= searchLength ; n++)

因为 word 的长度永远不会改变,所以你不需要每次都调用 strlen。在 for 循环之前创建一个变量来存储长度。

const int wordLength = strlen(word);    

我假设您要搜索的文本存储在 char 数组中。这意味着您需要将指针传递给存储在 n 中的第一个元素。

if (strncmp (&phrase[n],word,wordLength) == 0)

最后你会得到如下所示的东西:

char word[256] = "there";
char phrase[256] = "hello there hippie!";

const int wordLength = strlen(word);
const int searchLength = strlen(phrase);

for (int n = 0; n <= searchLength; n++)
{
// or phrase + n
if (strncmp(&phrase[n], word, wordLength) == 0)
{
return n;
}
}

return -1;

注意:最后一个示例现在已经完成,可以返回匹配。

关于c++ - 比较字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com