# string pattern recognition?

This is a discussion on string pattern recognition? within the C++ Programming forums, part of the General Programming Boards category; hi, the user inputs a line of like a hundred characters into one string and i'm using getline. what's the ...

1. ## string pattern recognition?

hi,

the user inputs a line of like a hundred characters into one string and i'm using getline.

what's the logically simple way to look for 5 letter words?

currently my program has a for loop inside which contains a large if statement that says:

Code:
`if ( isspace(line[i-1]) && isalpha(line[i]) && isalpha(line[i+1]) && isalpha(line[i+2]) && isalpha(line[i+3]) && isalpha(line[i+4]) && isspace(line[i+5]) )`
i just think that there might be a simpler string member function that would serve the same purpose if not handle it better.

thanks,
barneygumble742

2. Uh, right. And what exactly is he supposed to do with this function, search for every possible five-character word, with spaces on both sides? And what good does searching for "of" do in the string "Professor Hoffman offs lofty offers."?

I would go with something along the lines of:

Code:
```int last_nonalph = -1;
int e = str.size() + 1;
for (int i = 0; i < e; ++i) {
if (i == e  ||  !isalpha(str[i])) {
if (i - last_nonalph == 6) {
/* Do whatever you want with the range (last_nonalph + 1 .. i - 1) */
}
last_nonalph = i;
}
}```

3. It has nothing to do with the problem at hand.

4. if by 5 letter words you mean words that have 5 characters, all seperated by spaces, then you could use the strtok() function in a loop

http://www.cppreference.com/stdstring/strtok.html

note that won't work on lines like: "wow!! later" because that will count as two 5-letter words. what you could do, is after you find where the 5-letter word wannabe is, you could test each character with isalpha()

http://www.cppreference.com/stdstring/isalpha.html

that still doesn't guarantee that it's a real word, but it makes sure that it contains 5 characters from the alphabet (A-z).

5. i worked on several options, cause this interested me
and the code i choose to use at the end is this,
and it account for punctuation during a word
and at the end of the sentence.

Code:
```#include <iostream>
#include <ctype.h>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
string mystring;
string mystring2;
string size;
vector<string> tokens;
vector<string>::iterator forward;
cout << "Enter a sentence : ";
getline(cin, mystring, '\n');
stringstream ss(mystring);
while(ss >> mystring2)
{
tokens.push_back(mystring2);
}
int punct = 0;
for(forward = tokens.begin(); forward != tokens.end(); forward++)
{
size = *(forward);
for(int i = 0; i != size.size()-1; i++)
{
if(ispunct(size[i]))
{
punct++;
}
}
if(ispunct(size[size.size()-1]))
{
size.erase(size.size()-1, 1);
}
if((size.size()-punct) == 5)
{
cout << size << endl;
}
punct = 0;
}
cin.get();
return 0;
}```