C++ check if string is beginning of an english word - c++

I've found a couple answers for how to check if a string is a full word, but nothing for how to check if a string is the first part of a word.
For example, I need a function that will return true for "c", "b", "cong" (congratulations, congruent, etc.), or "exa" (example, examine, etc.), but false for "congx", "qt", or other gibberish.
I'd imagine there are a number of ways to go about this. If you could provide a rough outline for a strategy, I would really appreciate it.
I'm trying to make a Boggle solver.
Thanks!

Is std::string part contained in std::string word?
if(word.find(part) != std::string::npos)
{
// part is in word somethere
}
Is std::string part at the beginning of std::string word?
if(word.find(part) == 0)
{
// word starts with part
}
By way of explanation, std::string::find() returns the position of what was found. So 0 means it was found at the beginning. The value std::string::npos is a special value that indicates nothing was found at all.

Related

How to find a character in a string?

I have already checked topics similar to this one but no one has been able to solve this problem.
So, I have to look for a character inside a string but it doesn't seem to work.
if (tracciatonuovos.find('T'))
{
nterminale++;
}
The counter does not increase. But if I try to find an empty space, it counts for me, and yet the string is full
First value is string, second is length of string, and third is the value of counter "nterminale".
use the find function from the std::string class
std::string mystr = "Some String with T";
size_t apos = mystr.find("T");
Read more about it here
If you want to find the first occurrence use :
find_first_of
And if you want to repeatedly find all occurrences of a specific character you will also need to specify a search start position and will need to write a loop say something like :
size_t pos = 0;
while((pos = mystr.find(whatever, pos)) != std::string::npos)
{
pos +=1;
// and your other logic here
}

Is there alternative str.find in c++?

I have got a queue fifo type (first in, first out) with strings in it. Every string is sentence. I need to find a word in it, and show it on console. The problem is, that when i used str.find("word") it can showed sentence with "words".
Add white space and some symbols like ".,?!" = str.find("word ") etc. but its not a solution
if (head != nullptr)
do {
if (head->zdanie_kol.find("promotion") != string::npos ||
head->zdanie_kol.find("discount") != string::npos ||
head->zdanie_kol.find("sale") != string::npos ||
head->zdanie_kol.find("offer") != string::npos)
cout << head->zdanie_kol << endl;
} while (head != nullptr);
For example, i got two sentences, one is correct, another one is not.
Correct:
We have a special OFFER for you an email database which allows to contact eBay members both sellers and shoppers.
Not Correct:
Do not lose your chance sign up and find super PROMOTIONS we prepared for you!
The three simplest solutions I can think of for this are:
Once you get the result simply check the next character. If it's a whitespace or '\0', you found your match. Make sure to check the character before too so you don't match sword when looking for word. Also make sure you're not reading beyond the string memory.
Tokenize the string first. This will break the sentence into words and you can then check word by word to see if it matches. You can do this with strtok().
Use regular expression (e.g. regex_match()) as mentioned in the comments. Depending on the engine you choose, the syntax may differ, but most of them have a something like "\\bsale\\b" which will match on word boundary (see here for more information).
Here is a solution, using std::unordered_set and std::istringstream:
#include <unordered_set>
#include <string>
#include <sstream>
//...
std::unordered_set<std::string> filter_word = {"promotion", "discount", "sale", "offer"};
//...
std::istringstream strm(head->zdanie_kol);
std::string word;
while (strm >> word)
{
if (filter_word(word).count())
{
std::cout << head->zdanie_kol << std::endl;
break;
}
}
//...
If you had many more words to check instead of only 4 words, this solution seems easier to use since all you have to do is add those words to the unordered_set.

Cannot get second while to loop properly

I'm making a function that removes elements from a string. However, I cant seem to get both of my loops to work together. The first while loop works flawlessly. I looked into it and I believe it might be because when "find_last_of" isn't found, it still returns a value (which is throwing off my loop). I haven't been able to figure out how I can fix it. Thank you.
#include <iostream>
#include <string>
using namespace std;
string foo(string word) {
string compare = "!##$";
string alphabet = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
while(word.find_first_of(compare) < word.find_first_of(alphabet)) {
int position = word.find_first_of(compare);
word = word.substr(++position);
}
while(word.find_last_of(compare) > word.find_last_of(alphabet)){
int size = word.length();
word = word.substr(0, --size);
}
return word;
}
int main() {
cout << foo("!!hi!!");
return 0;
}
I wrote it like this so compound words would not be affected. Desired result: "hi"
It's not entirely clear what you're trying to do, but how about replacing the second loop with this:
string::size_type p = word.find_last_not_of(compare);
if(p != string::npos)
word = word.substr(0, ++p);
It's not clear if you just want to trim certain characters from the front and back of word or if you want to remove every one of a certain set of characters from word no matter where they are. Based on the first sentence of your question, I'll assume you want to do the latter: remove all characters in compare from word.
A better strategy would be to more directly examine each character to see if it needs to be removed, and if so, do so, all in one pass through word. Since compare is quite short, something like this is probably good enough:
// Rewrite word by removing all characters in compare (and then erasing the
// leftover space, if any, at the end). See std::remove_if() docs.
word.erase(std::remove_if(word.begin(),
word.end(),
// Returns true if a character is to be removed.
[&](const char ch) {
return compare.find(ch) != compare.npos;
}),
word.end());
BTW, I'm not sure why there is both a compare and alphabet string in your example. It seems you would only need to define one or the other, and not both. A character is either one to keep or one to remove.

string.find() doesn't return -1

The code below is simple. As I know, if string::find() didn't find matches it returns -1. But for some reasons the code below doesn't work. Everytime I run this code I get endless loop. Thank you for help!
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
text = "asdasd ijk asdasd";
string toReplace = "ijk";
cout<<text<<endl;
int counter = 0;
while ( text.find(toReplace) != -1)
counter++;
cout<<counter<<endl;
system("pause");
}
Aside from the other answers which are completely correct, I just wanted to add that your while loop would have produced an endless loop anyway. For example:
while(text.find(toReplace) != std::string::npos)
counter++;
will be an endless loop because it will keep trying to find the toReplace string in text and it will always find it (that's because find starts from the beginning of the string each time). This is probably not what you intended.
std::string::find returns std::string::npos if the searched substring is not found, not -1. The exact value of npos is implementation-defined, so use npos, as in
while ( text.find(toReplace) != std::string::npos)
Come to think of it, find couldn't return -1 even if it wanted to because the return type of find is specified to be std::size_t which is an unsigned type.
Additionally, find will always search for the first occurrence of the substring, no matter how many times you call it. If you want to iterate through all the occurrences you should use the overload of find which takes a second parameter - the position from which to start searching.
Whoever told you this or wherever you read it, it lied to you.
If std::string::find fails, it returns std::string::npos, which is not -1.
You should check the documentation about such things, when you're not sure.
So, your while will be something like:
while ( std::string::npos != text.find(toReplace) )
Regarding your comment:
UPDATE: I tried to use while ( text.find(toReplace) != string::npos ) but I still get endless loop :( – user2167403 10 secs ago
You should really learn to read the documentation. Use a variable to store the last result of std::string::find (different from std::string::npos) and use std::string::find's second parameter - pos ( by passing value - last_match_position + 1).
Omitting the second parameter, std::string::find always starts from the beginning of the string, which causes the endless loop.
In the code snippet you provided text variable contains substring "ijk" which is stored in the toReplace variable. As long as in while cycle neither text or toReplace variables are changed, find method will always return not a -1 value which is the condition for while cycle to continue.
As already metioned in other comments you should check not for -1 but for std::string::npos.
It does help to read the manual page (string::npos is the answer).
See http://www.cplusplus.com/reference/string/string/find/

check if WCHAR contains string

I have variable WCHAR sDisplayName[1024];
How can I check if sDisplayName contains the string "example"?
if(wcscmp(sDisplayName, L"example") == 0)
; //then it contains "example"
else
; //it does not
This does not cover the case where the string in sDisplayName starts with "example" or has "example" in the middle. For those cases, you can use wcsncmp and wcsstr.
Also this check is case sensitive.
Also this will break if sDisplayName contains garbage - i. e. is not null terminated.
Consider using std::wstring instead. That's the C++ way.
EDIT: if you want to match the beginning of the string:
if(wcsncmp(sDisplayName, L"Adobe", 5) == 0)
//Starts with "Adobe"
If you want to find the string in the middle
if(wcsstr(sDisplayName, L"Adobe") != 0)
//Contains "Adobe"
Note that wcsstr returns nonzero if the string is found, unlike the rest.
You can use the wchar_t variants of standard C functions (i.e., wcsstr).
wscstr will find your string anywhere in sDisplayName, wsccmp will see if sDisplayName is exactly your string.