给定一个s字符串和一个n字符串,在s字符串中找出n字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1(需要给出多个测试用例,证明算法的正确性)C语言。
时间: 2024-02-13 07:07:54 浏览: 39
以下是一个基于暴力匹配的算法示例:
```c
#include <stdio.h>
#include <string.h>
int find_first_position(char *s, char *n) {
int s_len = strlen(s);
int n_len = strlen(n);
for (int i = 0; i <= s_len - n_len; i++) {
int j;
for (j = 0; j < n_len; j++) {
if (s[i+j] != n[j])
break;
}
if (j == n_len)
return i;
}
return -1;
}
int main() {
char s1[] = "hello world";
char n1[] = "world";
printf("%d\n", find_first_position(s1, n1)); // expect 6
char s2[] = "hello world";
char n2[] = "test";
printf("%d\n", find_first_position(s2, n2)); // expect -1
return 0;
}
```
以上代码中,`find_first_position` 函数接受两个字符串参数 `s` 和 `n`,并返回 `n` 在 `s` 中第一次出现的位置(从0开始)。如果 `n` 在 `s` 中不存在,则返回 -1。
我们可以通过多个测试用例来验证该算法的正确性。在上面的示例代码中,我使用了两个测试用例来验证算法的正确性。