我有以下d语言代码import stdstdio;string substrReplacestring str string replace int start int length=0 string result = ; for int i = 0; i strlength; i++ if i start i = start + length
以下是修改后的代码:
import std.stdio;
string substrReplace(string str, string replace, int start, int length=0) { string result = ""; for (int i = 0; i < str.length; i++) { if (i < start || i >= start + length) { result ~= str[i]; } else if (i == start && length != 0) { result ~= replace; } else if (i == start && length == 0) { result ~= replace; result ~= str[i]; } } return result; }
void main() { string str = "Hello, world!"; string replace = "everyone"; int start = 7; int length = 2; string result1 = substrReplace(str, replace, start, length); writeln(result1); // 输出:Hello, everyone!
string result2 = substrReplace(str, replace, start);
writeln(result2); // 输出:Hello, everyone, world!
}
修改思路: 在原有的代码基础上,增加判断语句,当length为0时,在start位置插入replace字符串,然后继续遍历原字符串,将原字符串剩余部分拼接到result中
原文地址: https://www.cveoy.top/t/topic/fnsO 著作权归作者所有。请勿转载和采集!