像python一样的字符串索引在c++中。

时间:2021-11-05 22:30:53

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?

是否有(可能,使用宏)使用python表达式f(i:j)获取字符串的子字符串的方法?或者,更具体地说,解析i:j表达式为一对指数i和j?什么好主意吗?

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.

编辑:基本上,我想看看它是否广泛适用。对于数组,也许。所以问题更多的是a "我可以把I变成j I j"吗,我猜。不重要的是这些是std:字符串还是c字符串。

1 个解决方案

#1


17  

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.

警告:我是招聘经理。如果我发现你使用这种技术,我永远不会雇用你。

#1


17  

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.

警告:我是招聘经理。如果我发现你使用这种技术,我永远不会雇用你。