一个程序,它将字符串中的所有 s1 替换为 s2



我发现这个程序可以用字符串中的s2替换所有s1,但我不理解序列
int I=strstr(s,s1(-s?

enter code here
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *my_replace(char *s, char *s1, char *s2)
{
char *aux = (char *) malloc((sizeof(s) - sizeof(s1)) + sizeof(s2) + 1);
int i = strstr(s, s1) - s, j = strlen(s1);
strncpy(aux, s, i);
strcat(aux, s2);
strncat(aux, (s + i + j), (strlen(s) - i - j));
return aux;
}

int main()
{
char *s, *s1, *s2;
s = (char*)malloc(10);
s1 = (char*)malloc(10);
s2 = (char*)malloc(10);
char *aux;
scanf("%s%s%s", s, s1, s2);
aux = my_replace(s, s1, s2);
printf("%sn", aux);
return 0;
}

。。并且我不理解序列:int i = strstr(s, s1) - s

它给出了ss1的偏移量。

示例:

char* s = "abcdef";
char* s1 = "cd";
printf("%dn", strstr(s, s1) - s);

将给出结果2

这是因为strstr返回一个指向已定位子字符串开头的指针,然后通过对字符串的开头进行减法运算(指针算术(,可以获得它们之间的偏移量。

你可以这样看:

abcdr
^ ^
| | 
| strstr(s, s1)
|
s

相关内容

最新更新