4

Is there any (possibly, using a macros) way to get a substring of a string using python-like expression f(i:j)? Or, more specifically, resolve i:j expression into pair of indices i and j? Any ideas?

EDIT: Yes, I need :. Or ;. Basically, something that simple function or macros can't do. Just want to see if it is possible or not.

EDIT: Basically, I want to see if it is widely applicable. For arrays as well, maybe. So the question is more of a "Can I turn i:j to i j", I guess. Doesn't matter is these are std:strings or c-strings.

6
  • Are you very specific about the colon (:) in between i and j? Can you use comma (,)? Commented Jul 24, 2013 at 2:25
  • 7
    If you are in C++, write C++ code. Don't look for ways to make your C++ look like python. Commented Jul 24, 2013 at 2:30
  • 1
    The Python-like expression would be f[i:j]. Regardless of whether it's possible and/or good, is there are a reason why you want round brackets? Commented Jul 24, 2013 at 2:31
  • Are you using c-strings or std::string? Commented Jul 24, 2013 at 2:32
  • Whatever you do, don't abuse macros to do this in C++, that's a bad path down which to go. Commented Jul 24, 2013 at 2:33

1 Answer 1

22

I hate myself for answering, but ...

#include <iostream>
#include <string>

#define f(x) substr(true?x, false?x)

int main () {
  std::string s = "Hello, world";
  std::string y = s.f(1:4);
  std::cout << y << "\n";
}

Warning: I am a hiring manager. If I ever discover that you use this technique, I will never hire you.

Sign up to request clarification or add additional context in comments.

4 Comments

That's too brilliant to not upvote, even if it should never be used.
Maybe you should include a disclaimer at the end
That is great, thank you:) #define g(x) f(0 x) also allows g(:3) and other cool stuff:)
This answer is wrong. The output is "ello". In Python, the output for the expression s[1:4] would be "ell".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.