Cleaner code

Alright i am using the Find method to look in the users input, for certain words , but the code is long and kind of an eye sore , does anyone know of a way to write the code and make it shorter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <iostream>       
#include <string>

using namespace std;

int main ()
{
  std::string str ("There are two needls in this haystack with a needle.");
  std::string str2 ("There");
  std::string str3 ("needle");
  std::string str4 ("in");
  std::string str5 ("haystack");

  
  std::size_t found = str.find(str2);
  found = str.find(str3);
  found = str.find(str4);
  found = str.find(str5);
  if (found!=std::string::npos)
  {
	  // do something 
  }


  system("pause");

  return 0;
}
Last edited on
you could remove the std::'s from the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <windows.h>
#include <iostream>       
#include <string>

using namespace std;

int main ()
{
string str ("There are two needls in this haystack with a needle.");
string str2 ("There");
string str3 ("needle");
string str4 ("in");
string str5 ("haystack");

  size_t found = str.find(str2);
  found = str.find(str2);
  found = str.find(str2);
  found = str.find(str2);
  found = str.find(str2);
  if (found!=string::npos)
  {
	  // do something 
  }

  system("pause");

  return 0;
}
Last edited on
Alright thank you , no is there anything that can be done about the bottom half to condense it a bit
1
2
3
4
5
6
7
8
  size_t found = str.find(str2);
  found = str.find(str3);
  found = str.find(str4);
  found = str.find(str5);
  if (found!=string::npos)
  {
	  // do something 
  }
Last edited on
Do you realize that only the last found is evaluated since you overwrite the first three values? So if that is indeed what you want you could do:

1
2
3
4
5
if(str.find(str5) != string::npos)
{
   // do something.
}
Last edited on
and don't follow this advice:
you could remove the std::'s from the code.


For this reason:
http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>       
#include <string>

int main ()
{
  const std::string str = "There are two needles in this haystack with a needle." ;
  
  for( const std::string token : { "There", "needle", "in", "haystack" } )
  {
      if( str.find(token) != std::string::npos )
      {
          // do something
      }
  }
}
1
2
3
4
5
#include <iostream>       
#include <string>
using namespace std;
int main (){const string str = "There are two needles in this haystack with a needle." ;  
for( const string token : { "There", "needle", "in", "haystack" } ){if( str.find(token) != stdstring::npos ){/* do something*/}}}
Alright thank you but the code above is giving an error
Which code, what is the error?

If you're talking about the code by jasonwynn10, then yes there is at least one error. I suggest you use the code provided by JLBorges. And please please don't try to stuff so many things on so few lines as shown by jasonwynn10, it'll just make your programs harder to read and almost impossible to troubleshoot.

well with the code given by JLBorges i am getting a error right after the token : of expected an expression and i have tried everything i know of and it wont go away
1
2
3
4
5
6
7
8
9
 const std::string str = "There are two needles in this haystack with a needle." ;
  
  for( const std::string token : { "There", "needle", "in", "haystack" } )
  {
      if( str.find(token) != std::string::npos )
      {
          // do something
       }
   }
Last edited on
> for some reason it keeps giving an error C2059:syntax error after the token : on the {
> and i really dont know what might be happening here

It appears that you are using an old version of the Microsoft compiler.
Range-based loops and initializer_list<>s require C++11 support.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>       
#include <string>

int main ()
{
    const std::string str = "There are two needles in this haystack with a needle." ;

    const std::string tokens[] = { "There", "needle", "in", "haystack" } ;
    const std::size_t N = sizeof(tokens) / sizeof( tokens[0] ) ;

    for( std::size_t i = 0 ;  i < N ; ++i )
    {
          if( str.find( tokens[i] ) != std::string::npos )
          {
              // do something
          }
    }
}
Regex! Learn it, love it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <regex>
#include <string>

int main()
{
	const std::string sample = "There are two needles in this haystack with a needle."
	const std::string regex_str = "(there|needle|in|haystack)";
	std::regex example_regex(regex_str, regex_constants::icase);
	if(std::regex_search(sample, example_regex))
	{
		//Do something
	}
	return 0;
}


Not tested, but should work with minor or no changes. The regex_constants::icase just says to ignore case. So it'll match There, there, tHere, tHeRe, etc.
Resource for building and testing regular expressions: http://www.regexr.com/
@ResidentBiscuit
This doesn't work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main()
{
	const string sample = "There are two needles in this haystack with a needle.";
	const string regex_str = "(there|needle|in|haystack)";
	regex example_regex(regex_str, regex_constants::icase);
	if(regex_search(sample, example_regex))
	{
    cout<<"Hello World!";
	}
	return 0;
}

This outputs nothing!
Last edited on
Works for me. After actually going and reading the thread, your compiler may not actually support enough of C++11 to use <regex>, though. If you can grab an up-to-date version of Visual Studio, this will work. It ran just fine on my VS2013 Professional. You can get Professional for free with a *.edu email address, or if you're not a student you can get 2013 Express for free.

I highly recommend updating so you can use modern C++ features.
> This doesn't work ... This outputs nothing!

It doesn't have equivalent functionality: there is no std::match_results<> object to hold the sub-matches and there is no loop to iterate through the sub-matches.

std::regex_token_iterator<> comes in handy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <regex>

int main ()
{
    const std::string str = "There are two needles in this haystack with a needle." ;

    for( const std::string token : { "There", "needle", "in", "haystack" } )
    {
        if( str.find(token) != std::string::npos )
        {
            std::cout << "found: " << token << '\n' ;
        }
    }

    std::cout << "--------------------\n" ;

    const std::regex re( "(there|needle|in|haystack)", std::regex_constants::icase ) ;
    using iterator = std::sregex_token_iterator ;

    for( iterator iter( str.begin(), str.end(), re, 1) ; iter != iterator() ; ++iter )
    {
        std::cout << "found: '" << *iter << "' [" << iter->first - str.begin()
                  << ',' << iter->second - str.begin() << ")\n" ;
    }
}

http://rextester.com/WAEKB59457
If OP was just wanting to see if any of these strings were a substring of the first string, then what I posted works and is probably the simplest and cleanest solution.
Thanks all the code from JLBorges works great now that iv updated my compiler Thanks for all your help everyone
Ugh;
1
2
3
4
5
#include <iostream>       
#include <string>
using namespace std;
int main (){const string str = "There are two needles in this haystack with a needle." ;  
for( const string token : { "There", "needle", "in", "haystack" } ){if( str.find(token) != stdstring::npos ){/* do something*/}}}
Please use this as an example what NOT to do. Never put your main function in one line.
Topic archived. No new replies allowed.