finding a pattern of letters in a word

240 Views Asked by At

Is there any way that I can search for "tro_ _ _e" where the underscores represent missing letters?

I have a text file with a 7 letter word on each line. e.g

trouble
control
reached
further
helping
shatter
biggest

I am trying to compare each word to the string

char check[10]="tro\0\0\0e"

at the moment I am reading each line and comparing using:

if(strstr(pword,check)!=NULL)
{
    fprintf(wfile,"%s\n",pword);
    }
}

fclose(file);

fclose(wfile);

I realise that my current output in wfile:

control
trouble

is due to the fact that there are three \0s in between the "tro" and the "e" and so the comparison is just finding "tro" in the words.

Is there any way that I can search for "tro_ _ _e" where the underscores represent missing letters?

This is for a hangman game and so the words in the file are not always the same, not always 7 letters long and the pattern is not always "tro_ _ _e" as the pattern represents the letters already guessed by a player. The answer in this case: "trouble"

For example, if a player guessed "r", "u" and "l". I would have a string which was literally.

char check[10]="\0r\0u\0l\0\0\0\0\0" so the search I would want would be for any words with a pattern "_r_u_l"

4

There are 4 best solutions below

1
On

If you are truly open to a C# solution, as suggested by your tags:

string pword = "control\r\ntrouble\r\nreached\r\nfurther\r\nhelping\r\nshatter\r\nbiggest";
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("tro...e");
System.Text.RegularExpressions.MatchCollection mc = re.Matches(pword);
foreach (System.Text.RegularExpressions.Match m in mc)
{
   Console.WriteLine(m.Value);
}
2
On

I'm not entirely sure what your problem actually is but I guess you could combine two searches/conditions with AND, like: if(strstr(pword,check) != NULL && pword[6]=='e') ...

3
On

Don't mess with \0 - Every function in string.h think that it ends strings. Use _.

Probably you should write your own function. something like:

int isval(const char *word,const char *pat) {
 while (*word) {
  if (*pat!='_' && *pat!=*word) return 0;
  word++;
  pat++;
 }
 return !*pat;
}
0
On

Posix systems have <regex.h>, with regcomp, regexec and so forth, if you need an extensible solution.