#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int i = 0;
char c;
char *array;
char *data;
char *ret;
array = (char *) malloc(100);
data = (char *) malloc(strlen(argv[1])+1);
strcpy(data, argv[1]); // store the word john into the array called data
while((c=getchar())!=EOF) // stores the words in the txt file into array
{
array[i]=c;
i++;
}
ret = strstr(array, data); // find a substring (john in this case)
printf("The substring is: %s\n", ret);
*ret = "jack"; // Doesn't work here, but I want to replace john with jack
free(data);
free(array);
return 0;
}
我对 strstr 工具做了一些研究,它似乎找到了子字符串的第一次出现并返回指向该位置的指针。我想使用该指针修改它,但对我来说不太顺利。
当我运行它时,我在 Ubuntu 上的终端看起来像这样:
./a.out 约翰 <披头士.txt
我的披头士文本看起来像这样;
保罗
约翰
林戈
约翰
最后,我希望包含这 4 个名称的数组将 john 替换为 jack。无论如何,我可以使用 strstr 工具给我的指针来做到这一点吗?
我想我需要 while llop 或 for 循环来让数组中的每个 john 都被 jack* 替换
最佳答案
你不想修改指针,你想修改指针指向的东西。 ret
也指向一个字符,所以 *ret
是字符序列的第一个字符,在本例中是字符
'j'
,所以你不能只给它分配一个字符串。您必须替换该序列的每个字符。 memcpy
函数可以帮助您。
要替换其他出现的“john”,您可以使用此循环:
while(ret = strstr(array, data)){
printf("The substring is: %s\n", ret);
memcpy(ret, "jack", strlen("jack"));
}
strstr()
如果未找到任何内容,则返回 NULL
,当这种情况发生时,您将跳出循环。
你的代码也有一些问题:
- 您可以使用
argv[1]
代替data
。 - 最好通过调用
fread()
将文件复制到缓冲区。
关于c - 替换C中数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329140/