检查一个字符串是否在另一个没有指针的字符串中。

问题描述 投票:-1回答:1

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");
}
c arrays string substring c-strings
1个回答
0
投票

写一个程序,在另一个字符串中找到一个字符串,如果找到目标字符串,打印 "是",如果没有找到,打印 "否"。为了紧凑,你可以简单地写成。

#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

0
投票

有一个函数叫 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.