What i basically want is more than one character to be found. If h and a are in the string then it will print it. But it will only work if there is a single char.

#include <iostream>
#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,"ha"); //<<<<<<<Doesn't work - If i changed "ha" to 'h' then only h will be found
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,"ha");
  }
  system("pause");
  return 0;
}

Edited 5 Years Ago by Tom_Weston: n/a

If you examine the strchr prototype you'll note it doesn't take a c-string for the second parameter.

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

You'll have to do more than one search if you use this function.

Edited 5 Years Ago by gerard4143: n/a

To find if a letter is in the string then you can do

string sample = "have a good day.";
if (sample.find_firt_of("ha", 0) != string::npos)

The above example will only check to see if there is an 'h' or an 'a' in the string. It does not check to see if there together. If you want to see if the string contains a 'ha' in it you could do something like this.

size_t pos = 0;
string sample = "we will have stake";
while ((pos = sample.find_first_of("a", pos)) != string::npos)
{
    if (sample.find_first_of("a", pos) == pos + 1)
        cout << sample << "has an \'ha\' in it";
}

No no no.. You've mis understood me. So lets say the string is "The man ate all of the ham yesterday before we came home." I want the output to be:

e found
e found
etc....
and
o found
o found
etc...

No no no.. You've mis understood me. So lets say the string is "The man ate all of the ham yesterday before we came home." I want the output to be:

e found
e found
etc....
and
o found
o found
etc...

Your example doesn't make sense. What are you looking for?

The issue is here:

pch=strchr(pch+1,"ha");

You are only moving up your string one character at a time, but in your example you have two characters (ha). Try this:

pch=strchr(pch+2,"ha");
This article has been dead for over six months. Start a new discussion instead.