dlang语言原生实现php的sub_str函数类似sub_strstring input int start int length = -1这样负数表示截至到字符串末尾第几个字符位置length=-1默认表示截取到字符串倒数第一个字符的位置另外尽量不要用标准库给出完整可以运行的例子感谢您的回答
以下是一个简单的实现:
string sub_str(string input, int start, int length = -1) {
if (start < 0) {
start = input.length + start;
}
if (length < 0) {
length = input.length - start;
}
return input[start..start + length];
}
void main() {
string input = "Hello, world!";
writeln(sub_str(input, 7, 5)); // 输出 "world"
writeln(sub_str(input, -6)); // 输出 "world!"
}
这个实现首先处理start和length的默认值,然后根据start和length计算出需要截取的子字符串。在处理start时,如果start是一个负数,则将其转换为相对于字符串末尾的位置。在处理length时,如果length是-1,则将其设为从start开始到字符串末尾的长度。最后,使用D语言的切片操作符从原始字符串中提取子字符串
原文地址: https://www.cveoy.top/t/topic/fm8S 著作权归作者所有。请勿转载和采集!