Srini
Srini

Reputation: 173

Need to know about c++ strchr function and how it works

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

For example:

realm=strchr(name,'@');

What is the meaning for this line?

Upvotes: 0

Views: 7168

Answers (3)

TomeeNS
TomeeNS

Reputation: 460

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)

Upvotes: 0

RvdK
RvdK

Reputation: 19790

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 = "[email protected]";
char* realm = strchr(name,'@');

//realm will point to "@hello.com"

Upvotes: 2

Pulkit Goyal
Pulkit Goyal

Reputation: 5654

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

Upvotes: 3

Related Questions