0

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 by Tom_Weston: n/a

4
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by MonsieurPointer
0

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 by gerard4143: n/a

0

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";
}
0

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...

0

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?

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.