我是 C 指针的新手,我正在尝试编写一个类似于高级编程语言的 String.IndexOf() 函数的程序。
基于 String.indexOf function in C ,我已经开始工作了:
int main() {
int index;
char* source = "test string";
char* found = strstr( source, "in" );
if (found != NULL) {
index = found - source;
}
printf("%d\n", index); // prints 8.
return 0;
}
但是当我尝试将其用作函数时,我总是得到 0。(例如,第一个字符串为“Hello World”,然后“World”将打印“0”而不是预期值“6”)。
基本上,stdin 的第一行是“source”(或“haystack”)字符串,接下来的几行将是“needle”。
// includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char master[120];
// returns the index of the substring
int substr(char* needle) {
int index;
char* found = strstr( master, needle );
if (found != NULL) {
index = found - needle;
}
printf("%d\n", index);
return index;
}
int main() {
char input[120];
int timesCalled = 0;
while(fgets(input, 120, stdin)) {
timesCalled++;
if (timesCalled == 1) {
strcpy(master, input);
} else {
substr(input);
}
}
if (timesCalled == 0) {
fprintf(stderr, "Master String is empty");
return 1;
}
return 0;
}
这是怎么回事?当它被设置为全局变量时,“master”的指针会改变吗? “input”的指针作为参数传递时是否发生变化?为什么它在程序版本中有效?
欢迎任何意见。
编辑!
我已经将 strcpy(input, master)
行更改为 strcpy(master, input)
并且我仍然得到相同的结果!
最佳答案
问题一
您以错误的顺序将参数传递给 strcpy
。
它需要是:
strcpy(master, input);
第一个参数是目的地,第二个参数是源。
问题2
此外,由于 fgets()
也读取换行符,因此您没有在大海捞针中找到 needle
。在尝试搜索之前,您需要删除换行符。
问题3
您使用了错误的指针来计算 substr
中的索引。
index = found - needle;
需要
index = found - master;
问题4
您需要将index
初始化为某物。否则,当大海捞针中找不到 needle
时,它会返回一个未初始化的值。
int substr(char* needle) {
int index = -1; // Make the return value negative when needle is not found
char* found = strstr( master, needle );
if (found != NULL) {
index = found - master;
}
printf("%d\n", index);
return index;
}
固定程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char master[120];
// returns the index of the substring
int substr(char* needle) {
int index = -1;
char* found = strstr( master, needle );
if (found != NULL) {
index = found - master;
}
printf("%d\n", index);
return index;
}
void removeNewline(char* input)
{
size_t len = strlen(input);
if ( input[len-1] == '\n' )
{
input[len-1] = '\0';
}
else
{
printf("No newline found\n");
}
}
int main() {
char input[120];
int timesCalled = 0;
while(fgets(input, 120, stdin)) {
removeNewline(input);
timesCalled++;
if (timesCalled == 1) {
strcpy(master, input);
} else {
substr(input);
}
}
if (timesCalled == 0) {
fprintf(stderr, "Master String is empty");
return 1;
}
return 0;
}
输入:
test string
in
es
输出:
8
1
关于c - IndexOf 函数在 C 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683545/