I've just started c programming and the task is to write a program to find a string in another string and if the target string was found print "Yes" and if it wasn't print "No".I've written a function to do the above task but it doesn't quite work.if anyone could tell me what's wrong with my code I'll be thankful.
void substring (char source[], char target[]){
int i = 0;
int j = 0;
int counter = 0;
int a = strlen(target);
int b = strlen(source);
while (source[i] != 0){
while (target[j] != 0){
if (target[j] == source[i])
for (int k = 1; k < a; k++){
if (target[j + k] == source[i + k])
counter += 1;
}
j++;
}
i++;
}
if (counter == a)
printf("Yes\n");
else
printf("No\n");
}
写一个程序,在另一个字符串中找到一个字符串,如果找到目标字符串,打印 "是",如果没有找到,打印 "否"。为了紧凑,你可以简单地写成。
#include <stdio.h>
#include <string.h>
int main(){
char source[4] = "test";
char target[40] = "kkwkdnaxdtesttestkdkdtest";
int n = 0;
int found = 0;
while(n < strlen(target)+1-strlen(source)){
if (!strncmp(source,&target[n],strlen(source))) found++;
n++;
};
if (found) printf("yes %d\n", found);
else printf("no\n");
return 0;
}
Output:
yes 3
有一个函数叫 strstr
在C语言中,这正是你的工作。
仔细看一下 此处.
#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "This is a simple string";
char Target[] = "simple";
char *firstOccurrenceOfTarget = strstr(source, Target);
if (firstOccurrenceOfTarget == NULL)
{
printf("No\n");
}
else
{
printf("Yes\n");
}
return 0;
}