c - 函数 strrchr 的奇怪行为

标签 c string strrchr

我用 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/

相关文章:

c - 使用 strrchr 函数时出现段错误

c++ - 寻找具有特定功能的多边形几何库

在函数中调用函数指针作为参数

PHP 提取字符串的一部分

c++ - 用户输入文件路径

Java:从输入字符串数组生成 nCr 数组并返回它

c - 如何从 strrchr() 或 strchr() 中提取剩余的子字符串?

c - 函数参数无效

c - 如何从http获取文本文件到变量中