我用谷歌搜索,但没有运气.
我想要删除字符串的第一个字符,如下所示:
string s = "hello, world";
string t = cast(string) s[1..$]; // OK
string u = s[1..$]; // ERROR, can't cast char[] to string.
Run Code Online (Sandbox Code Playgroud)
好吧,我可能会错过一些东西.cast(string)使代码更难以理解.
有没有更简单的方法来获取子串(没有强制转换)?
Ada*_*ppe 11
你根本不应该去那里,这些都是字符串.
如果s是a char[],您可以通过指定它来强制它为字符串(就像您在示例中所做的那样),或者用于to!string(s)转换它.to!string在模块中找到std.conv.
之后,你有一致的类型的一切,做字符串时,切片是好的,像你在那里做,但如果在它的非ASCII字符你可能要小心一点.string [1 .. $]会删除第一个字节,但字符可能是多个字节.
如果你import std.utf;,你将有一个名为strideavailable 的函数可以检查多字节字符.
string t = s[s.stride() .. $]; // chops off the first character*, even if it is multi-byte
Run Code Online (Sandbox Code Playgroud)
但一般来说,我会说用其他函数获取索引,然后对其进行切片.所以,如果你想要子世界,请:
import std.string;
auto index = s.indexOf("world");
if(index == -1) throw new Exception("substring 'world' not found");
auto world = s[index .. $]; // gets the substring starting from world to the end of string
Run Code Online (Sandbox Code Playgroud)
像这样的函数indexOf可以为您处理多字节字符的复杂性.