检查 D 中字符串是否在数组中?
如何检查数组中是否出现字符串? 我的意思是我当然可以循环,但是有标准功能吗?
起初我这样做了:
if(str in ["first", "second", "third"])
但它抱怨 in
仅适用于关联数组。
我尝试快速查找 phobos 文档,但没有找到任何与数组相关的模块。
那么有什么吗,或者我只需要手动循环它?
编辑:
我在 D1,福波斯。
How do I check for a string occurance in an array? I mean sure I can loop, but is there a standard function?
at first I did:
if(str in ["first", "second", "third"])
but it complained that in
only works with associative arrays.
I tried to quickly lookup the phobos docs but didn't find any module related to arrays.
So is there anything, or do I just have to loop through it manually?
Edit:
I'm on D1, phobos.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的字符串是常量(如示例中所示),您可以使用关联数组文字,但语法不太漂亮:
我认为没有可以在 D1 的 Phobos 中使用的库调用,但 D2 的 std.algorithm 有您可以使用的东西:
在 Tango 中,您可以使用
tango.text.Util
中的通用contains
函数:请注意,
[]
位于数组文字末尾是必需的,因为我们需要传递静态数组的内存切片,而不是按值传递实际的静态数组。If your strings are constant (like in the example), you can use an associative array literal, but the syntax isn't pretty:
I don't think there's a library call you can use in D1's Phobos, but D2's std.algorithm has something you could use:
In Tango, you can use the generic
contains
function fromtango.text.Util
:Note that the
[]
at the end of array literals is required because we need to pass a memory slice of the static array, and not the actual static array by-value.对于 D1 Phobos,您必须自己动手。 但这并不太难。
另外,您应该能够像这样使用它:
希望有帮助。
顺便说一句,您可以修改上面的内容以用作“indexOf”函数:
With D1 Phobos, you'll have to do it yourself. But it's not too hard.
Plus, you should be able to use it like this:
Hope that helps.
Incidentally, you can modify the above to work as an "indexOf" function: