我用 strrchr 得到了一些奇怪的结果。请帮助我。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char szString[32] = "hello-world-and-everyone";
char* ptemp = NULL;
ptemp = strrchr(szString, '-');
if (ptemp == NULL)
{
printf("Invalid string\n");
return 1;
}
printf("%s\n", szString);
printf("%s\n", ptemp );
*ptemp = 0;
printf("%s\n", szString);
return 0;
}
预期结果:
hello-world-and-everyone
-everyone
hello-world-and-everyone
实际结果:
hello-world-and-everyone
-everyone
hello-world-and
最佳答案
实际结果是正确的(这应该不足为奇,真的)。
前两行输出符合您的预期,因此我假设您已经很好地理解了它们。这是最后两行中发生的事情:第一行(赋值)在最后一个破折号的位置以 null 终止 szString
:
*ptemp = 0; // Replaces the last dash '-' with '\0'
所以字符串变成了
h e l l o - w o r l d - a n d \0 e v e r y o n e \0
当您现在打印它时,printf
找到第一个终止符,并在那里停止。这就是为什么您会在输出中看到截断的字符串,而不是原始字符串。
关于c - 函数 strrchr 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177434/