【问题标题】:Difference between strchr and strpbrkstrchr 和 strpbrk 的区别
【发布时间】:2016-10-06 17:45:11
【问题描述】:

strchr()strpbrk() 有什么区别。我找不到它们之间的任何区别。

strpbrk():

#include <stdio.h>
#include <string.h>
int main()
{
        char str1[30] = "New Delhi is awesome city", str2[10] = "an";
        char *st;
        st = strpbrk(str1, str2);
        printf("%s"st);
        return 0;
}

输出:awesome city

strchr()

#include <stdio.h>
#include <string.h>
int main()
{
        char str1[] = "New Delhi is awesome city", ch = 'a';
        char *chpos;
        chpos = strchr(str1, ch);
        if(chpos)
                printf("%s",chpos);
        return 0;
}

输出:awesome city

【问题讨论】:

  • 第一种情况,尝试使用字符串中的两个字符进行搜索,如"wa"
  • 它们给出了相同的输出,因为在str1 中“a”出现在“n”之前。事实上,“n”根本没有出现在str1 中。尝试将str2 设置为“as”,你会看到它给出了不同的输出。
  • "...找不到它们之间的任何区别。" --> 然而代码调用一个char *,另一个调用int。嗯。
  • 虽然它们起初看起来很神秘,但man strchrman strpbrk(实际上是所有手册页)在解释使用、操作、返回和错误报告以及参数方面做得非常出色C 库中每个函数的列表(在汇编编程中也很有用)。

标签: c string stdio


【解决方案1】:

文档很清楚。来自strchr()strpbrk()

char *strpbrk(const char *s, const char *accept);

       The strpbrk() function locates the first occurrence in the string s
       of any of the bytes in the string accept.


char *strchr(const char *s, int c);

       The strchr() function returns a pointer to the first occurrence of
       the character c in the string s.

基本上,strpbrk() 允许您指定要搜索的多个字符。 在您的示例中,strchr()strpbrk() 在找到字符 'a' 后都会停止,但这并不意味着它们会做同样的事情!

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 2011-05-04
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多