0

I want to know about strchr function in C++.

For example:

realm=strchr(name,'@');

What is the meaning for this line?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Srini
  • 173
  • 1
  • 2
  • 4

3 Answers3

3

From here.

Returns a pointer to the first occurrence of character in the C string str.

The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}

will produce output

Looking for the 's' character in "This is a sample string"...
found at 4
found at 7
found at 11
found at 18
Pulkit Goyal
  • 5,604
  • 1
  • 32
  • 50
2

www.cplusplus.com is a very usable site for C++ help. Such as explaining functions.

For strchr:

Locate first occurrence of character in string Returns a pointer to the first occurrence of character in the C string str.

The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

char* name = "hi@hello.com";
char* realm = strchr(name,'@');

//realm will point to "@hello.com"
RvdK
  • 19,580
  • 4
  • 64
  • 107
0

Just for those who are looking here for source code/implementation:

char *strchr(const char *s, int c)
{
    while (*s != (char)c)
        if (!*s++)
            return 0;
    return (char *)s;
}

(origin: http://clc-wiki.net/wiki/strchr)

TomeeNS
  • 455
  • 4
  • 10