How would I search an element in a vector string? - c++

I'm trying to search a vector string for certain words.
For example,
vector<string> sentences = ["This is a test string","Welcome to C++!"];
string searchString = "This";
I tried
if (std::find(sentences.begin(), sentences.end(), searchString) != sentences.end()) {
cout << "Found!";
}
else {
cout << "Not Found!";
}
Now this does work but only if the searchString matches the element word for word.
For example if we set
string searchString = "This is a test string";
This will return found.
How do I search the elements individually?
Thanks!

for(std::string& s : sentences)
{
if(s.find(searchString) != std::string::npos)
{
//substring found
}
else
{
//substring not found
}
}
this should work for looking for a word in each string in the vector

There is std::find_if that lets you pass a predicate to be used instead of directly comparing elements for equality with a searchString:
auto matcher = [searchString](const std::string& element) {
return element.find(searchString) != std::string::npos;
};
if (std::find_if(sentences.begin(), sentences.end(), matcher) != sentences.end()){
cout << "Found!";
} else {
cout<< "Not Found!";
}

You can iterate over all the strings in your vector and check each string one by one if it contains the string you want to find. If the string contains the search term, you can return the whole element:
#include <iostream>
#include <vector>
#include <string>
std::string findSubstr(const std::vector<std::string>& list, const std::string& search) {
for (const std::string& str : list) {
if (str.find(search) != std::string::npos) {
return str;
}
}
return "Not found";
}
int main(int argc, const char** argv) {
if (argc < 2) {
std::clog << "Usage: " << argv[0] << " <search term>\n";
return 1;
}
std::vector<std::string> test{"This is a test string", "Welcome to C++!"};
std::cout << findSubstr(test, argv[1]) << std::endl;
}

Related

For every instance of a character/substring in string

I have a string in C++ that looks like this:
string word = "substring"
I want to read through the word string using a for loop, and each time an s is found, print out "S found!". The end result should be:
S found!
S found!
Maybe you could utilize toupper:
#include <iostream>
#include <string>
void FindCharInString(const std::string &str, const char &search_ch) {
const char search_ch_upper = toupper(search_ch, std::locale());
for (const char &ch : str) {
if (toupper(ch, std::locale()) == search_ch_upper) {
std::cout << search_ch_upper << " found!\n";
}
}
}
int main() {
std::string word = "substring";
std::cout << word << '\n';
FindCharInString(word, 's');
return 0;
}
Output:
substring
S found!
S found!

Check user input by each char if exists in char array [duplicate]

I want to write a function that determines if all the letters of an inputted word are contained in another string of acceptable letters.
bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
// ... how do I write this?
}
Here's my testing framework:
bool Tester(std::string inputtedWord, std::string acceptableLetters)
{
if (ContainsOnly(inputtedWord, acceptableLetters)) {
std::cout << "Good!" << std::endl;
return true;
}
else {
std::cout << "No good!" << std::endl;
return false;
}
}
int main()
{
std::string acceptableLetters;
std::string inputtedWord;
std::cout << "Please input the acceptable letters in your words: " << std::endl;
std::cin >> acceptableLetters;
while (inputtedWord != "STOP")
{
std::cout << "Please input the word you would like to test: (type STOP to end testing): " << std::endl;
std::cin >> inputtedWord;
Tester(inputtedWord, acceptableLetters);
}
return 0;
}
I want the following output:
Please input the acceptable letters in your words: CODING
Please input the word you would like to test: (type STOP to end testing): COIN
Good!
Please input the word you would like to test: (type STOP to end testing): COP
No good!
You can use find_first_not_of like this:
bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
return inputtedWord.find_first_not_of(acceptableLetters) == std::string::npos;
}
Here's a demo.
Put all the acceptable characters to std::set.
Judge if all characters in the strings are in the set via std::all_of.
#include <set>
#include <algorithm>
bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
std::set<char> okSet(acceptableLetters.begin(), acceptableLetters.end());
return std::all_of(inputtedWord.begin(), inputtedWord.end(),
[&okSet](char c)
{
return okSet.find(c) != okSet.end();
});
}

How to run a string search algorithm through whole body of text

I am using the brute force string search algorithm to search through a small sentence, however I want the algorithm to return every time it finds the certain string instead of finding it once and then stopping
//Declare and initialise variables
string pat, text;
text = "This is a test sentence, find test within this string";
cout << text << endl;
//User input for pat
cout << "Please enter the string you want to search for" << endl;
cin >> pat;
//Set the length of the pat and text
int patLength = pat.size();
int textLength = text.size();
//Algorithm
for (int i = 0; i < textLength - patLength; ++i)
{
//Do while loop to run through the whole text
do
{
int j;
for (j = 0; j < patLength; j++)
{
if (text[i + j] != pat[j])
break; // Doesn't match here.
}
if (j == patLength)
{
finds.push(i); // Matched here.
}
} while (i < textLength);
}
//Print output
cout << "String: " << pat << " was found at positions: " << finds.top();
The program stores each find in a queue. When I run this program, it asks for the 'pat', then does nothing. I have done a bit of debugging and found that it is probably the do while loop. However I can't find a fix
You could use the std::string::find function combined with a function that you call for each find.
#include <iostream>
#include <functional>
#include <vector>
#include <sstream>
void Algorithm(
const std::string& text, const std::string& pat,
std::function<void(const std::string&,size_t)> f, std::vector<size_t>& positions)
{
size_t pos=0;
while((pos=text.find(pat, pos)) != std::string::npos) {
// store the position
positions.push_back(pos);
// call the supplied function
f(text, pos++);
}
}
// function to call for each position in which the pattern is found
void gotit(const std::string& found_in, size_t pos) {
std::cout << "Found in \"" << found_in << "\" # " << pos << "\n";
}
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv+1, argv+argc);
if(args.size()==0)
args.push_back("This is a test sentence, find test within this string");
for(const auto& text : args) {
std::vector<size_t> found_at;
std::cout << "Please enter the string you want to search for: ";
std::string pat;
std::cin >> pat;
Algorithm(text, pat, gotit, found_at);
std::cout << "collected positions:\n";
for(size_t pos : found_at) {
std::cout << pos << "\n";
}
}
}
My first bit of advice would be to structure your code into separate functions.
Let's say you have a function that returns the position of the pattern's first occurrence in a sequence of characters:
using position = typename std::string::const_iterator;
position first_occurrence(position text_begin, position text_end, const std::string& pattern);
If there is no more occurrence of the pattern, it returns text_end.
You can now write a very simple loop:
auto occurrence = first_occurrence(text_begin, pattern);
while (occurrence != text_end) {
occurrences.push_back(occurrence);
occurrence = first_occurence(occurrence + 1, text_end, pattern);
}
to accumulate all the occurrences of the pattern.
The first_occurrence function already exists in the standard library under the name of std::search. Since C++17, you can customize this function with pattern-searching specialized searchers, such as std::boyer_moore_searcher: it pre-processes the pattern to make it faster to look for in the string. Here's an example application to your problem:
#include <algorithm>
#include <string>
#include <vector>
#include <functional>
using occurrence = typename std::string::const_iterator;
std::vector<occurrence> find_occurrences(const std::string& input, const std::string& pattern) {
auto engine = std::boyer_moore_searcher(pattern.begin(), pattern.end());
std::vector<occurrence> occurrences;
auto it = std::search(input.begin(), input.end(), engine);
while (it != input.end()) {
occurrences.push_back(it);
it = std::search(std::next(it), input.end(), engine);
}
return occurrences;
}
#include <iostream>
int main() {
std::string text = "This is a test sentence, find test within this string";
std::string pattern = "st";
auto occs = find_occurrences(text, pattern);
for (auto occ: occs) std::cout << std::string(occ, std::next(occ, pattern.size())) << std::endl;
}

Difficulties with string declaration/reference parameters (c++)

Last week I got an homework to write a function: the function gets a string and a char value and should divide the string in two parts, before and after the first occurrence of the existing char.
The code worked but my teacher told me to do it again, because it is not well written code. But I don't understand how to make it better. I understand so far that defining two strings with white spaces is not good, but i get out of bounds exceptions otherwise. Since the string input changes, the string size changes everytime.
#include <iostream>
#include <string>
using namespace std;
void divide(char search, string text, string& first_part, string& sec_part)
{
bool firstc = true;
int counter = 0;
for (int i = 0; i < text.size(); i++) {
if (text.at(i) != search && firstc) {
first_part.at(i) = text.at(i);
}
else if (text.at(i) == search&& firstc == true) {
firstc = false;
sec_part.at(counter) = text.at(i);
}
else {
sec_part.at(counter) = text.at(i);
counter++;
}
}
}
int main() {
string text;
string part1=" ";
string part2=" ";
char search_char;
cout << "Please enter text? ";
getline(cin, text);
cout << "Please enter a char: ? ";
cin >> search_char;
divide(search_char,text,aprt1,part2);
cout << "First string: " << part1 <<endl;
cout << "Second string: " << part2 << endl;
system("PAUSE");
return 0;
}
I would suggest you, learn to use c++ standard functions. there are plenty utility function that can help you in programming.
void divide(const std::string& text, char search, std::string& first_part, std::string& sec_part)
{
std::string::const_iterator pos = std::find(text.begin(), text.end(), search);
first_part.append(text, 0, pos - text.begin());
sec_part.append(text, pos - text.begin());
}
int main()
{
std::string text = "thisisfirst";
char search = 'f';
std::string first;
std::string second;
divide(text, search, first, second);
}
Here I used std::find that you can read about it from here and also Iterators.
You have some other mistakes. you are passing your text by value that will do a copy every time you call your function. pass it by reference but qualify it with const that will indicate it is an input parameter not an output.
Why is your teacher right ?
The fact that you need to initialize your destination strings with empty space is terrible:
If the input string is longer, you'll get out of bound errors.
If it's shorter, you got wrong answer, because in IT and programming, "It works " is not the same as "It works".
In addition, your code does not fit the specifications. It should work all the time, independently of the current value which is stored in your output strings.
Alternative 1: your code but working
Just clear the destination strings at the beginning. Then iterate as you did, but use += or push_back() to add chars at the end of the string.
void divide(char search, string text, string& first_part, string& sec_part)
{
bool firstc = true;
first_part.clear(); // make destinations strings empty
sec_part.clear();
for (int i = 0; i < text.size(); i++) {
char c = text.at(i);
if (firstc && c != search) {
first_part += c;
}
else if (firstc && c == search) {
firstc = false;
sec_part += c;
}
else {
sec_part += c;
}
}
}
I used a temporary c instead of text.at(i) or text\[i\], in order to avoid multiple indexing But this is not really required: nowadays, optimizing compilers should produce equivalent code, whatever variant you use here.
Alternative 2: use string member functions
This alternative uses the find() function, and then constructs a string from the start until that position, and another from that position. There is a special case when the character was not found.
void divide(char search, string text, string& first_part, string& sec_part)
{
auto pos = text.find(search);
first_part = string(text, 0, pos);
if (pos== string::npos)
sec_part.clear();
else sec_part = string(text, pos, string::npos);
}
As you understand yourself these declarations
string part1=" ";
string part2=" ";
do not make sense because the entered string in the object text can essentially exceed the both initialized strings. In this case using the string method at can result in throwing an exception or the strings will have trailing spaces.
From the description of the assignment it is not clear whether the searched character should be included in one of the strings. You suppose that the character should be included in the second string.
Take into account that the parameter text should be declared as a constant reference.
Also instead of using loops it is better to use methods of the class std::string such as for example find.
The function can look the following way
#include <iostream>
#include <string>
void divide(const std::string &text, char search, std::string &first_part, std::string &sec_part)
{
std::string::size_type pos = text.find(search);
first_part = text.substr(0, pos);
if (pos == std::string::npos)
{
sec_part.clear();
}
else
{
sec_part = text.substr(pos);
}
}
int main()
{
std::string text("Hello World");
std::string first_part;
std::string sec_part;
divide(text, ' ', first_part, sec_part);
std::cout << "\"" << text << "\"\n";
std::cout << "\"" << first_part << "\"\n";
std::cout << "\"" << sec_part << "\"\n";
}
The program output is
"Hello World"
"Hello"
" World"
As you can see the separating character is included in the second string though I think that maybe it would be better to exclude it from the both strings.
An alternative and in my opinion more clear approach can look the following way
#include <iostream>
#include <string>
#include <utility>
std::pair<std::string, std::string> divide(const std::string &s, char c)
{
std::string::size_type pos = s.find(c);
return { s.substr(0, pos), pos == std::string::npos ? "" : s.substr(pos) };
}
int main()
{
std::string text("Hello World");
auto p = divide(text, ' ');
std::cout << "\"" << text << "\"\n";
std::cout << "\"" << p.first << "\"\n";
std::cout << "\"" << p.second << "\"\n";
}
Your code will only work as long the character is found within part1.length(). You need something similar to this:
void string_split_once(const char s, const string & text, string & first, string & second) {
first.clear();
second.clear();
std::size_t pos = str.find(s);
if (pos != string::npos) {
first = text.substr(0, pos);
second = text.substr(pos);
}
}
The biggest problem I see is that you are using at where you should be using push_back. See std::basic_string::push_back. at is designed to access an existing character to read or modify it. push_back appends a new character to the string.
divide could look like this :
void divide(char search, string text, string& first_part,
string& sec_part)
{
bool firstc = true;
for (int i = 0; i < text.size(); i++) {
if (text.at(i) != search && firstc) {
first_part.push_back(text.at(i));
}
else if (text.at(i) == search&& firstc == true) {
firstc = false;
sec_part.push_back(text.at(i));
}
else {
sec_part.push_back(text.at(i));
}
}
}
Since you aren't handling exceptions, consider using text[i] rather than text.at(i).

How to return a certain boolean value in a recursive function?

I want to make a recursive function that determines if a string's characters all consist of alphabets or not. I just can't figure it out. Here's what I've done so far but it doesn't work properly.
bool isAlphabetic(string s){
const char *c = s.c_str();
if ((!isalpha(c[0]))||(!isalpha(c[s.size()])))
{
return false;
}
else if (isalpha(c[0]))
{
isAlphabetic(c+1);
return true;
}
}
can anyone suggest a correct way?
Leaving aside the many partial strings you'll create (consider passing in just the string and a starting index instead), the isalpha(c[s.size()]) check will always fail, since that's the \0 at the end of the string. You're also ignoring the result of the recursive calls.
bool isAlphabetic(string s){
if (s.size() < 1)
return true; // empty string contains no non-alphas
const char *c = s.c_str();
if (!isalpha(c[0]))
{
return false; // found a non-alpha, we're done.
}
else
{
return isAlphabetic(c+1); // good so far, try the rest of the string
}
}
Building on Paul's answer, here is a fixed implementation that won't copy any portion of the string. It accomplishes this by passing a reference to the string object and an index to the character to check; recursion simply adds 1 to this index to check the next character, and so on until the end of the string is found.
I have removed your call to c_str() since it isn't needed. string can be directly indexed.
bool isAlphabetic(string const & s, int startIndex = 0) {
// Terminating case: End of string reached. This means success.
if (startIndex == s.size()) {
return true;
}
// Failure case: Found a non-alphabetic character.
if (!isalpha(s[startIndex])) {
return false;
}
// Recursive case: This character is alphabetic, so check the rest of the string.
return isAlphabetic(s, startIndex + 1);
}
Note that the empty string is considered alphabetic by this function. You can change this by changing return true to return !s.empty().
Here a working example:
#include <iostream>
#include <string>
using namespace std;
bool isAlphabetic(string s)
{
if( s.empty() )
{
return false;
}
cout << "checking: " << s[0] << endl;
if( isalpha(s[0]) )
{
return true;
}
return isAlphabetic(&s[0]+1);
}
int main()
{
string word0 = "test";
if( isAlphabetic(word0) )
{
cout << word0 << " is alphabetic" << endl;
}
else
{
cout << word0 << " is NOT alphabetic" << endl;
}
string word1 = "1234";
if( isAlphabetic(word1) )
{
cout << word1 << " is alphabetic" << endl;
}
else
{
cout << word1 << " is NOT alphabetic" << endl;
}
string word2 = "1234w";
if( isAlphabetic(word2) )
{
cout << word2 << " is alphabetic" << endl;
}
else
{
cout << word2 << " is NOT alphabetic" << endl;
}
return 0;
}