C 中的子字符串计数
我的一个朋友需要帮助计算字符串中子字符串的出现次数,我想出了以下代码。有谁知道更好的方法来做到这一点?
#include "stdio.h"
#include "string.h"
int main(int argc, char *argv[])
{
char str1[50], str2[50];
int i, j, l1, l2, match, count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
l1 = strlen(str1);
l2 = strlen(str2);
count = 0;
for(i = 0; i < l1; i++)
{
match = 0;
for(j = 0; j < l2; j++)
{
if(str1[i + j] == str2[j])
{
match++;
}
}
if(match == l2)
{
count++;
}
}
printf("Substrings: %d\n", count);
}
A friend of mine needed help counting the occurrences of a substring in a string, and I came up with the following code. Does anyone know a better method to do this?
#include "stdio.h"
#include "string.h"
int main(int argc, char *argv[])
{
char str1[50], str2[50];
int i, j, l1, l2, match, count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
l1 = strlen(str1);
l2 = strlen(str2);
count = 0;
for(i = 0; i < l1; i++)
{
match = 0;
for(j = 0; j < l2; j++)
{
if(str1[i + j] == str2[j])
{
match++;
}
}
if(match == l2)
{
count++;
}
}
printf("Substrings: %d\n", count);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请不要使用或鼓励使用
gets
。除了它会在代码中引入故障点这一事实之外,它已从 C99 起被弃用,并将从 C1X 中完全消失。正如其他人所说,
strstr
是你的朋友:Please do not use or encourage the use of
gets
. Beyond the fact that it will introduce a point of failure in your code, it has been deprecated as of C99 and will be gone completely from C1X.As others have said,
strstr
is your friend here:您可能想看看 strstr 函数(如果您还不熟悉它)。
You might want to take a look at the strstr function (if you're not already familiar with it).
上面的代码可以工作,但这是静态的。
Above code works but this is static.
您可以在QT库中使用QString
You can use QString in QT library
怎么样:(使用
strstr
函数,参考这里< /a>)how about this: (using the
strstr
function, reference here)