我有一个如下所示的数组:
char test[100]
然后我想比较这个数组是否有这个特定的句子
if (test == "yup this is the sentence") {
// do stuff
}
这是对的吗?有更好的方法吗?谢谢。
答案 0 :(得分:3)
你不能在C中做到这一点。你在这里做的是检查身份相等(如果你的两个指针指向相同的内存区域,则为id est。)
你可以做的就是使用符合你想要的libc strstr
:
#include <string.h>
if (strstr(test, "yup this is the sentence") != NULL)
{
// do stuff if test contains the sentence
}
在终端中输入man 3 strstr
以获取有关该功能及其所有行为的更多信息。
如果你想了解函数的行为,这里用纯C重新编码,只有一个循环:
char *strstr(const char *s1, const char *s2)
{
int begin;
int current;
begin = 0;
current = 0;
if (!*s2)
return ((char *)s1);
while (s1[begin])
{
if (s1[begin + current] == s2[current])
current++;
else
{
current = 0;
begin++;
}
if (!s2[current])
return ((char *)s1 + begin);
}
return (0);
}
它是学校项目的一部分。完整项目包含所有C库基本功能。
您可以在此处查看其他一些字符串操作函数: https://github.com/kube/libft/tree/master/src/strings
答案 1 :(得分:2)
您可以使用var b = {
length: 0,
map: Array.prototype.map,
constructor: { // yes, usually a function
[Symbol.species]: MyArray
}
};
var mapped = b.map(x => x*x);
console.log(mapped instanceof MyArray); // true
:
strstr
或者您可以使用一些指针算法:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void) {
char test[256] = "This is a looooooonnnnggggg string which contains ('yup this is the sentence') my needed string inside";
if (strstr(test, "yup this is the sentence") != NULL){
printf("True\n");
}else{
printf("False\n");
}
return 0;
}
输出:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void checkString(char *string1, char *string2);
int main(void){
char test[256] = "This is a looooooonnnnggggg string which contains ('yup this is the sentence') my needed string inside";
char string2[] = "yup this is the sentence";
checkString(test, string2);
return 0;
}
void checkString(char *string1, char *string2){
char *s1, *s2, *s3;
size_t lenstring1 = strlen(string1);
size_t lenstring2 = strlen(string2);
if (lenstring2 < 1){
printf("There is no substring found");
exit(1);
}
size_t i=0,j=0;
int found=0;
s1 = string1;
s2 = string2;
for(i = 0; i < lenstring1; i++){
if(*s1 == *s2){
s3 = s1;
for(j = 0;j < lenstring2;j++){
if(*s3 == *s2){
s3++;s2++;
}else{
break;
}
}
s2 = string2;
if(j == strlen(string2)){
found = 1;
printf("%s\nwas found at index : %zu\n",string2,i+1);
}
}
s1++;
}
if(found == 0){
printf("No match Found");
}
}