如何扫描字符串以查找特定术语

时间:2015-02-25 06:04:11

标签: c arrays string

我试图扫描特定单词的用户输入文本,然后,当这些单词出现时,将它们打印到控制台。

#import <Foundation/Foundation.h>
#include <stdio.h>

int main(){
char cArray[] = "example";
char cInput[] = "";
char cOutput[] = "";

printf("\nType your message:\n");
for (int y=0; y<1; y++){
    fgets(cInput, 120, stdin);
}
printf("\nInitialised character array:\n");
for (int x=0; x<1; x++){
    if(strncmp(&cInput[x], &cArray[x], 120) == 0){
        strncpy(cOutput, cArray, strnlen(cInput, +1));
        printf("%s\n", cOutput);
        break;
        }
    }
}

输出:

Type your message:
example

Initialised character array:
Program ended with exit code: 120

感谢任何反馈,因为我还在学习:)

感谢。

编辑后的代码:

#include <stdio.h>
#include <string.h>

#define MAX_STR_LEN 120

int main(){
char *cArray[MAX_STR_LEN] = {"example", "this"};
char cInput[MAX_STR_LEN] = "";
char cOutput[MAX_STR_LEN] = "";

printf("Type your message:\n");
for (int y=0; y<1; y++){
    fgets(cInput, MAX_STR_LEN, stdin);
    char * ptr = cInput;
    while((ptr=strstr(ptr, *cArray)) != NULL){
        strncpy(cOutput, ptr, strlen(*cArray));
        printf("Initialised string array:\n%s\n", cOutput);
        ptr++;
        }
    }
}

虽然我现在遇到了不同的问题,但仍有效。输出似乎只在一个单词完成之前注册,因此只有&#34;例如&#34;打印出来。

输出:

Type your message:
this is an example
Initialised string array:
example
Program ended with exit code: 0

2 个答案:

答案 0 :(得分:2)

char cInput[] = "";

此数组的大小为1.

fgets(cInput, 120, stdin);

这是数组越界写入,这将导致未定义的行为。

有无

char cInput[120] = "";

你需要照顾

char cOutput[120] = "";

也。由于您在比较后尝试写入此数组。

答案 1 :(得分:1)

你需要来自string.h的strstr函数

const char * strstr ( const char * str1, const char * str2 );

以下为您提供了一个使用示例:

#include <stdio.h>
#include <string.h>

#define MAX_STR_LEN 120

int main(){
    char cArray[MAX_STR_LEN] = "example";  // string to be searched in the input string
    char cInput[MAX_STR_LEN] = ""; // input string
    char cOutput[MAX_STR_LEN] = ""; // buffer for found string

    printf("\nType your message:\n");
    for (int y=0; y<1; y++){     // this loop from original example looks strange, but it works
        fgets(cInput, MAX_STR_LEN, stdin);
    }
    // search in the input string
    char * ptr;
    if( ( ptr=strstr(cInput, cArray) ) != NULL)
    {
        //copy the string to cOutput
        strncpy(cOutput, ptr, strlen(cArray));
        // output the found string
        printf("String that was found: \n%s\n", cOutput);
    }
    else
    {
        printf("String was not found in the input!\n");
    }
}

修改

如果您想要所有字符串,请使用以下循环而不是if-else

    // search in the input string
    char * ptr = cInput;
    while( ( ptr=strstr(ptr, cArray) ) != NULL)
    {
        //copy the string to cOutput
        strncpy(cOutput, ptr, strlen(cArray));
        // output the found string
        printf("String \"%s\" was found at position %d\n", cOutput, (int)(ptr - cInput + 1));
        // find next string
        ptr++;
    }