How do you find the substring within a string in a set? For example, if I enter "Ville," then Louisville, Gainesville, and Muellerville are found? I have tried the following code
for(string const& search : cities)
{
if(find(search.begin(), search.end(), str) != std::string::npos)
{
string y = search;
employees.emplace_back(y);
,but I cannot figure out what is wrong with my syntax. This code is used in the following project (Project Code)
EDIT: My problem was simple and was fixed with using .begin() and .end() to iterate over the multimap name_address and finding each name with .substr. I also used a multimap instead of a set. I found the syntax easier and got it to work.
for(auto it = name_address.begin(); it != name_address.end(); ++it)
{
for(int i = 0; i < it->first.length(); ++i)
{
string tmpstr3 = it->first.substr(0 + i, str.length());
if(str == tmpstr3)
{
employees.insert(it->second);
break;
}
}
}
You are likely looking for
if (search.find(str) != std::string::npos)
The std::find call you have shouldn't compile.
Related
Trying to solve the problem using C++ constructs. Reference to each word in the sentence is taken and reversed. But the changes are not seen in the original sentence.
class Solution {
public:
string reverseWords(string s) {
istringstream ss(s);
for(auto w = istream_iterator<string>(ss); w != istream_iterator<string>(); w++)
{
/* changes of the below 2 lines are not reflected in the main sentence*/
string &str = const_cast<string&>(*w);
reverse(str.begin(),str.end());
}
reverse(s.begin(),s.end());
return s;
}
};
I don't think it is possible to use streams without copying the word as the stream would always extract the word into a separate string. In your attempt, you are also modifying such a copy, that's why you get the original string returned. I would just use iterators (this is to be taken as pseudo-code, may not compile):
auto last = s.begin();
auto cur = s.begin();
while (cur != s.end()) {
if (!isalpha(*(cur++))) {
reverse(last, cur);
last = cur;
}
}
reverse(last, cur);
return s;
i made a simple code for a problem solving question but the result is weird for me
here is the code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,num;
string opr;
cin>>n;
num = 0;
for(int i = 1; i <= n; i++){
cin>>opr;
if(opr.find("++"))
{
num+=1;
}
else if(opr.find("--"))
{
num-=1;
}
}
cout<<num;
}
if i input n as number "1" it actually subtract and the result is -1
but if i inserted n as 2 or more it works fine
what is happening?
std::string::find doesn't work that way:
if(opr.find("++"))
you want:
if (opr == "++")
or if you just want to see if opr contains the substring "++":
if (opr.find("++") != std::string::npos)
The problem is that std::string::find does not return a bool -- rather it returns the index at which it found the substring or std::string::npos if it doesn't find it. Since that is a number (actually a size_t) it can be implicitly converted to a bool and thus tested, but the result is not what you want. You need something like:
if(opr.find("++") != std::string::npos)
{
num+=1;
}
else if(opr.find("--") != std::string::npos)
{
num-=1;
}
if you are looking for the existence of a substring in the input.
It's in the form of a word so let's say I'm given the string "foo", and inside my array there are words like "food", "fool", "foo". All three of them should be printed out.
I haven't made a solid attempt at it yet cause I don't know how to wrap my head around it. Any idea?
Assuming you're using std::string, you could use string::find to see if one string is contained in another.
If you have a vector of strings, you might use that along with (for example) std::remove_copy_if to print out all the words from the vector that contain the chosen word:
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
int main() {
std::vector<std::string> words{"food", "fool", "foo", "tofoo", "lood", "flood"};
std::string word = "foo";
std::remove_copy_if(words.begin(), words.end(),
std::ostream_iterator<std::string>(std::cout, "\n"),
[&](std::string const &s) {
return s.find(word) == std::string::npos;
});
}
Result:
food
fool
foo
tofoo
You could do something simple, like iterating through each character in the string and checking it against the characters in the string you are trying to match using a separate function. If three characters in a row match the string you are searching for, add it to a vector or something and display them.
// Variables
bool charMatched = false;
vector<string> *stringVec = new vector<string>();
int index = 0;
int counter = 0;
string str = "Whatever you are trying to match";
for (char &c : strings[index]) // For each character in string
{
// Check for match
if (checkChar(c))
{
counter++;
charMatched = true;
if(counter == str.length())
stringVec->push_back(strings[index]);
}
else
{
index++;
counter = 0;
break;
}
}
bool checkChar(char c)
{
// Iterator to go through match string
static string::iterator it = str.begin();
if (c == *it)
{
if (it == str.end())
it = str.begin(); // Reset iterator
else
it++; // Increment iterator
return true;
}
else
{
if (it == str.end())
it = str.begin(); // Reset iterator
else
it++; // Increment iterator
return false;
}
}
You will have to tweak it a little to work with an array the way you want it to but something like this should do what you want. I did not run this through a compiler, I wrote it in Notepad so there may be small syntax errors. I hope this helps!
I'm testing a small program in order to create a larger one.
I have a vector of 3 strings:
pass
pass
TEST pass pass
I want to search the vector for the substring "pass" and record how many times "pass" is found in the vector of strings.
So basically I want it to return the number 4 (4 instances of the substring "pass")
Code looks like this
the strings are stored in the vector myV1
if (find(myV1.begin(), myV1.end(), "pass") != myV1.end() )
{
passes++;
}
when I do this it finds "pass" once and ignores the others.
I can't get a loop to work either. It tells me that it found however many instances of the substring "pass" for as many times as i loop through.
Thanks in advance for any advice
In short: here you can find the working code with an online compiler.
All you need is two loops, one for iterating over the vector elements, and one that iterates over each element while counting the desired word occurrence in that particular element. The external loop summarizes it then.
You could use string::find for the internal loop, and the external loop is the regular one with the iterators.
You will need the snippet below to work properly with C++98/03 and C++11 as well.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<string> stringList;
stringList.push_back("pass");
stringList.push_back("pass");
stringList.push_back("Test pass pass");
string searchWord = "pass";
int searchWordSize = searchWord.size();
int count = 0;
for (vector<string>::iterator iter = stringList.begin(); iter != stringList.end(); ++iter) {
// Avoid the overlapping search word. If that is needed, replace
// pos+=searchWordSize with ++pos
for (size_t pos = 0; pos < (*iter).length(); pos+=searchWordSize) {
pos = (*iter).find(searchWord, pos);
if (pos != string::npos)
++count;
else
break;
}
}
cout << "Count: " << count << endl;
return 0;
}
I have built and run the code with the following commands:
g++ main.cpp
./a.out
The output will be 4 as expected.
You could loop vector and use std::string::find to find the occurrence of "pass" in each string.
To count occurrence of a substring correctly, you need to record postion of first occurrence then increment position and continue the search.
int count(const std::string& s, const std::string token = "pass")
{
int n(0);
std::string::size_type pos = s.find(token);
while (pos != std::string::npos)
{
pos = s.find(token, pos + 1);
n++;
}
return n;
}
int main()
{
std::vector<std::string> v = {"pass", "pass", "TEST pass pass"};
int total(0);
for (auto& w : v)
{
total += count(w);
}
std::cout << total << std::endl;
}
i have a long string variable and i want to search in it for specific words and limit text according to thoses words.
Say i have the following text :
"This amazing new wearable audio solution features a working speaker embedded into the front of the shirt and can play music or sound effects appropriate for any situation. It's just like starring in your own movie"
and the words : "solution" , "movie".
I want to substract from the big string (like google in results page):
"...new wearable audio solution features a working speaker embedded..."
and
"...just like starring in your own movie"
for that i'm using the code :
for (std::vector<string>::iterator it = words.begin(); it != words.end(); ++it)
{
int loc1 = (int)desc.find( *it, 0 );
if( loc1 != string::npos )
{
while(desc.at(loc1-i) && i<=80)
{
i++;
from=loc1-i;
if(i==80) fromdots=true;
}
i=0;
while(desc.at(loc1+(int)(*it).size()+i) && i<=80)
{
i++;
to=loc1+(int)(*it).size()+i;
if(i==80) todots=true;
}
for(int i=from;i<=to;i++)
{
if(fromdots) mini+="...";
mini+=desc.at(i);
if(todots) mini+="...";
}
}
but desc.at(loc1-i) causes OutOfRange exception... I don't know how to check if that position exists without causing an exception !
Help please!
This is an excellent exercise in taking advantage of what the STL has to offer. You simply open a reference and cherry-pick algorithms and classes for your solution!
#include <iostream> // algorithm,string,list,cctype,functional,boost/assign.hpp
using namespace std;
struct remove_from {
remove_from(string& text) : text(text) { }
void operator()(const string& str) {
typedef string::iterator striter;
striter e(search(text.begin(), text.end(), str.begin(), str.end()));
while( e != text.end() ) {
striter b = e;
advance(e, str.length());
e = find_if(e, text.end(), not1(ptr_fun<int,int>(isspace)));
text.erase(b, e);
e = search(text.begin(), text.end(), str.begin(), str.end());
}
}
private:
string& text;
};
int main(int argc, char* argv[])
{
list<string> toremove = boost::assign::list_of("solution")("movie");
string text("This amazing new wearable ...");
for_each(toremove.begin(), toremove.end(), remove_from(text));
cout << text << endl;
return 0;
}
You can just check desc.size() - if it's less than the index you're looking up + 1 then you'll get an exception
The problem is that you start iterating at the first word, then try and check the word before it, hence the OutOfRange Exception.
Your first if could be:
if( loc1 != string::npos && loc1 != 0)