1

I have a wstring (or wchar_t, whichever fits better), I want to compare it to 6 possible strings (which half of it is dynamic, not constant) with single IF statement (if possible). I want to know what's best approach for doing it, instead of several lines and lots of building strings and variables. I want to know professional/shortest/fastest/best way.

In nutshell, I want to do this: If MyStr was equal to :

MyCurrentFolder() + "test" OR MyCurrentFolder() + "test," OR MyCurrentFolder() + "test, " OR "test" OR "test, " OR "test," 

do something...

Please advice.

4
  • Is MyCurrentFolder() guaranteed to contain at leas one character not in those suffixes? Like / or \? Commented Aug 22, 2014 at 23:19
  • @Deduplicator Yes, guaranteed Commented Aug 22, 2014 at 23:24
  • "shortest/fastest", pick one, as they are likely to be mutually exclusive. Commented Aug 22, 2014 at 23:26
  • Fastest would be: Check for prefix-match, then check for full-match on the rest (without prefix if matched). Do not copy. Commented Aug 22, 2014 at 23:30

3 Answers 3

1

It think something like this would work:

bool any_of(std::string const& name, std::initializer_list<std::string> const& list) { return list.end() != std::find(list.begin(), list.end(), name); } // ... if (any_of(MyStr, { MyCurrentFolder() + "test", MyCurrentFolder() + "test,", MyCurrentFolder() + "test, ", std::string("test"), std::string("test,"), std::string("test, ") })) { ... } 
Sign up to request clarification or add additional context in comments.

3 Comments

Even knowing who you are, I question your use of std::string as a UnaryPredicate...
A touch of metamagic eliminates needless copying of strings to the heap: coliru.stacked-crooked.com/a/8b4daf1c6e3335cd, though there's a lot to be said for sticking to std.
@MooingDuck: I haven't really used std::any_of() and it seems I'd be better off using std::find(). I shall fix the example...
0

You could do it using std::set, assuming MyCurrentFolder returns a std::string. E.g.:

auto tests = std::set<std::string>{ MyCurrentFolder() + "test", MyCurrentFolder() + "test,", MyCurrentFolder() + "test, ", "test", "test, ", "test,"}; if (tests.find(MyStr) != tests.end()) { // matches } 

1 Comment

I'd recommend using std::vector<std::string> in combination with std::find(): it is likely a lot faster than using std::set<std::string> (primarily because it needs fewer allocations and has a much smaller memory footprint).
0

The following meets the requirement of fitting everything in an if-condition:

if ([&](wstring s) {vector<wstring>e{ MyCurrentFolder() + L"test", MyCurrentFolder() + L"test,", MyCurrentFolder() + L"test, ", L"test", L"test, ", L"test," }; return find(e.begin(), e.end(), s) != e.end(); }(MyStr)) { ...//YES the string is there; } 

Comments