= '-';或= '/'在strchr中意味着什么(我知道它确实定位了工作和最近发生的strrchr )?
这段代码确实创建了两个文件。
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fpA = fopen("output_A.txt", "w");
FILE *fpB = fopen("output_B.txt", "w");
char *strA = ",-/";
char temp[100];
char str[5][60] = { { "summer is coming!" },
{ "vacation will let you chill out" },
{ "and, have a nice time" },
{ "and, stay fit" },
{ "and, wish you the best" }, };
fprintf(fpA, "%s\n", str[0]);
fprintf(fpB, "%s\n", str[1]);
fclose(fpA);
fclose(fpB);
fpA = fopen("output_A.txt", "r");
fpB = fopen("output_B.txt", "w");
*(strchr(str[2], ' ')) = '-';
*(strrchr(str[2], ' ') + 1) = '/';
strtok(str[2], strA);
strcpy(temp, strtok(NULL, strA));
str[1][8] = '\n';
str[1][9] = '\0';
strncat(temp, str[1], strlen(str[1]));
if (strcmp(str[3], str[4]))
strcat(temp, str[3]);
else
strcat(temp, str[4]);
fprintf(fpA, "%s", temp);
fprintf(fpB, "%s", temp);
fclose(fpA);
fclose(fpB);
return 0;
}发布于 2022-06-09 06:56:17
声明
*(strchr(str[2], ' ')) = '-';
*(strrchr(str[2], ' ') + 1) = '/'; 基本上,将'-'替换为第一个空格,将'/'替换为最后一个空格出现旁边的字符。
第一个替代:
strchr返回指向搜索字符(' ')第一次出现的指针。*操作符访问该指针'-'第二个替代:
strrchr返回指向搜索字符(' ')最后一次出现的指针。*操作符访问指针'/'字符串str[2] (最初的"and, have a nice time" )将被更改为"and,-have a nice /ime"。
警告:您需要检查strchr和strrchr返回值,因为如果找不到搜索的字符,它们可以返回NULL (签出这 )。
如果是这样的话,取消指针将导致未定义的行为(可能是现代计算机上的分段错误),从而导致程序崩溃。
发布于 2022-06-09 06:52:47
它搜索' ',然后将'-'分配到它发现的第一个/最后一个' '出现的位置(取决于strchr,strrchr)。我不知道它为什么要这么做,但这就是代码所要做的。
Sidenote:strchr和strrchr在字符串中找不到delimiter匹配时返回NULL。如果字符串没有空格,则代码将出现分段错误。
一项改进可以是:
char* aux = strchr(str[2], ' ');
if (aux != NULL)
*aux = '-';https://stackoverflow.com/questions/72555762
复制相似问题